Finding common characters in two strings

前端 未结 13 2596
终归单人心
终归单人心 2020-12-15 14:09

I am coding for the problem in which we got to count the number of common characters in two strings. Main part of the count goes like this

for(i=0; i < st         


        
13条回答
  •  长情又很酷
    2020-12-15 14:47

    First, your code does not run in O(n^2), it runs in O(nm), where n and m are the length of each string.

    You can do it in O(n+m), but not better, since you have to go through each string, at least once, to see if a character is in both.

    An example in C++, assuming:

    • ASCII characters
    • All characters included (letters, numbers, special, spaces, etc...)
    • Case sensitive

    std::vector strIntersect(std::string const&s1, std::string const&s2){
    
        std::vector presents(256, false);  //Assuming ASCII
        std::vector intersection;
    
        for (auto c : s1) {
            presents[c] = true;
        }
        for (auto c : s2) {
            if (presents[c]){
                intersection.push_back(c);
                presents[c] = false;
            }
        }
        return intersection;
    }
    
    int main() {
        std::vector result; 
        std::string s1 = "El perro de San Roque no tiene rabo, porque Ramon Rodriguez se lo ha cortado";
        std::string s2 = "Saint Roque's dog has no tail, because Ramon Rodriguez chopped it off";
    
        //Expected: "S a i n t   R o q u e s d g h l , b c m r z p"
    
        result = strIntersect(s1, s2);
        for (auto c : result) {
             std::cout << c << " ";
        }
        std::cout << std::endl;
    
        return 0;
    }
    

提交回复
热议问题