[RainbowSecret] use istringstream to solve string related problem

  • 0

    Thanks to the post from @StefanPochmann

    At my first glance, I want to implement my split function to split the str to a vector of string array.

    Then we just check one word and one char step by step to make sure that the relationship OK!

    Using the istringstream can avoid the split problem, just use >> to read the string word one by one is ok!

    Here is the post from @StefanPochmann

    class Solution {
        bool wordPattern(string pattern, string str) {
            map<char, int> p2i;
            map<string, int> w2i;
            istringstream in(str);
            int i=0, n=pattern.size();
            for(string word; in>>word; i++){
                /** i==n means the length of word dict and the pattern not match **/
                if(i==n || p2i[pattern[i]]!=w2i[word])
                    return false;
            return i==n;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.