【问题标题】:Finding a Pair of character in a string [duplicate]在字符串中查找一对字符[重复]
【发布时间】:2020-09-26 15:28:54
【问题描述】:
#include<bits/stdc++.h>
using namespace std;

int main(){
    int t;
    cin >> t;
    while(t--){
        int count = 0;
        vector<string> v;
        string resp;
        cin >> resp;
        v.push_back(resp);
        for(int i = 0; i < v.size(); i++){
            if(find(v.begin(), v.end(), "xy") != v.end()){
                count++;
        }
        cout << count << endl;
   }
   return 0;
}

我想在多个测试用例的字符串中找到字符“xy”。 对于输入 xy,我的计数值正确输出为 1。

但是对于输入 xyxxy 而不是 2 它给出的值为 0 它只找到一次值,但我想检查整个字符串中 xy 的计数

我也尝试使用 substring 函数,但它失败了

【问题讨论】:

标签: c++ string data-structures stl substring


【解决方案1】:

我不明白 while 循环,但它对我有用。

#include <iostream>
#include <vector>

int main()
{
    std::string str;
    std::cin >> str;
    int count = 0;
    for (int i(0); i < str.size()-1; ++i)
    {
        if ((str[i] == 'x') && (str[i + 1] == 'y'))
        {
            ++count;
        }
    }
    std::cout << count;
}

【讨论】:

    【解决方案2】:

    您正在字符串向量中查找“xy”,在您的示例中,该向量具有单个元素“xyxxy”。由于“xy”不等于“xyxxy”,因此您找不到任何匹配项。

    但是,即使您尝试在“xyxxy”本身内使用std::find“xy” - 那也会失败,因为std::find 在一个范围内(或者更确切地说,迭代器)寻找一个单个元素对)。

    相反,您可以使用string::find() 方法,如here 所述;或者,视情况而定,std::string_view::find():

    #include <string>
    #include <vector>
    #include <iostream>
    #include <string_view>
    
    int main() {
        const std::string needle{"xy"};
        std::string haystack;
        std::cin >> haystack;
        std::size_t count{0};
        std::string_view remainder{haystack};
        while(true) {
            auto first_pos = remainder.find(needle);
            if (first_pos == std::string_view::npos) { break; }
            count++;
            remainder = remainder.substr(first_pos+needle.length());
        }
        std::cout << "Found " << count << " occurrences of \"" << needle << "\"\n";
    }
    

    注意:这不考虑重叠事件。如果你想要这些,你可以总是将起始位置增加 1;或者通过使用 Boyer-Moore 或 Knuth-Morris-Pratt 搜索(请参阅 String search algorithms)使您的解决方案更复杂,并在每次找到后恢复到正确的状态。

    【讨论】:

    • 它使用更多的内存空间。你有什么解决方案需要最小的空间复杂度?
    • @RAGHAVENDRADUBEY:这使用了O(1) 额外空间;我不确定你是什么意思。也许你混淆了std::string_viewstd::string
    • @RAGHAVENDRADUBEY:发给你我的什么?无论如何,答案可能是否定的。
    • 你能帮我解决我最近的问题吗?
    • 我在使用此解决方案时遇到 TLE 错误。 S 只能包含字母 X 和 Y。而 S 的大小为 N。而 N 的大小在 1-10^5 之间。所有测试用例的 N 总和不超过 3⋅
    猜你喜欢
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    • 2019-11-17
    • 2020-02-24
    • 1970-01-01
    相关资源
    最近更新 更多