【问题标题】:comparing in order c++按顺序比较 C++
【发布时间】:2017-12-19 21:44:30
【问题描述】:

注意:问题已解决!感谢您的所有帮助

我想从用户那里得到两个字符串(s1,s2) 并检查 s1 是否存在于 s2 中。 我写了下面的代码。它会找到字符串,但它不关心字母的顺序。 我怎样才能改变它,例如

s1="abcd" & s2="ooabzzzzzzcd" 它必须说是,而且确实如此。 s1="abcd" & s2="aczzzzzzzzbd" 它必须说不,但它没有 我也想要它,所以如果一个字母被使用了两次,它不会像这样混淆顺序 s1="mammid" & s2="ammizzzzd" 在这种情况下,我的程序会说是

PS。我使用了 s3 并在它的第一个放了一个“x”,只是为了把我从比较中得到的字符串放在另一个字符串中。我把“x”放在 s1 的第一个,所以不会有问题

    #include <iostream>
  #include <string>
  using namespace std;
  int main()
  {
    std::string s1;
    std::string s2;
    std::string s3="x ";    
   int x,y=0,i,cow;
   std::getline(std::cin, s1);
    std::getline(std::cin, s2);

    for ( cow = 0; cow < s2.size(); cow++)
    {
    for( i=cow;i<s2.size();i++){
        if (s1[cow] == s2[i]){
            s3=s3+s2[i];
            cout<<s3<<endl;
            break;
        }
       }
     }
     //the problem is with the part on top
    s1="x "+s1;

    if (s1 == s3)
        std::cout << "YES";

    if (s1 != s3)
    std::cout << "NO";
    return 0;
    }

【问题讨论】:

  • 对于s1="mammid" &amp; s2="ammizzzzd"的情况,为什么会返回yes? s2中的a前没有m。
  • 在 Stack Overflow 上将问题标记为已解决的方法是接受(单击复选标记)答案:)

标签: c++ string-comparison


【解决方案1】:

你需要重新考虑你的算法。

据我所知,以下似乎是不变量:

  • s2必须包含s1中的所有字母,
  • 按照它们在s1中出现的顺序,
  • 但不一定是连续的

这是我想出的:

/**
 * str == s2
 * substr == s1
 */
bool contains_in_order(std::string const& str, std::string const& substr) {
    size_t sub_index = 0;
    //We iterate through each character in the larger string, in order
    for (char const& c : str) {
        //Whenever we find a matching character, we advance the index.
        if (c == substr[sub_index]) sub_index++;
        //If the index has reached the end of the substring, we're done.
        if (sub_index >= substr.size()) break;
    }
    //If we didn't reach the end of the substring, we didn't find the whole substring.
    return sub_index >= substr.size();
}

然后我们可以像这样重写您的main 函数:

#include <iostream>
#include <string>

int main() {
    std::string s1;
    std::string s2; 

    std::getline(std::cin, s1);
    std::getline(std::cin, s2);

    bool found = contains_in_order(s2, s1);

    if (found) std::cout << "YES" << std::endl;
    else std::cout << "NO" << std::endl;

    return 0;
}

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 2014-06-25
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    相关资源
    最近更新 更多