search

Home  >  Q&A  >  body text

c++ - 【LeetCode】Word Pattern

我在 LeetCode 上练习 Word Pattern(题目连接点这里),写的程序放在本地VS2008上跑如下实例:

pattern = "abba", str = "dog cat cat fish" should return false.

没有问题,返回的是false,但是放在LeetCode 上提交,提示错误,错误如下:

代码如下:

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        const int len = pattern.length();
        char * c = new char[len+1];
        strcpy(c, pattern.c_str() );
        char * arr[1024];
        int num = 0;
        char * pch;
        pch = strtok(c, " ");
        while (pch != NULL)
        {
            arr[num++] = pch;
            pch = strtok(NULL, " ");
        }

        vector<char> vecStr;
        vector<char *> vecPattern;

        for (int i = 0; i < num; ++i)
        {
            for (int j = 0; j < vecStr.size(); ++j)
            {
                if (vecStr[j] == str[i] && *(vecPattern[j]) != *(arr[i]) )
                {
                    return false;
                }
            }

            for (int j = 0; j < vecPattern.size(); ++j)
            {
                if (*(vecPattern[j]) == *(arr[i]) && vecStr[j] != str[i])
                {
                    return false;
                }
            }

            vecStr.push_back(str[i]);
            vecPattern.push_back(arr[i]);
        }

        return true;
    }
};

求指教。

怪我咯怪我咯2882 days ago749

reply all(1)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 13:07:28

    I ran your code and found that it is wrong. Why, because

        pch = strtok(c, " ");
        while (pch != NULL)
        {
            arr[num++] = pch;
            pch = strtok(NULL, " ");
        }

    Your c here should be str, but you pointed to pattern.

    And I think pattern and str may have been messed up in your mind after you wrote it, and you have to continue to change it.

    reply
    0
  • Cancelreply