c++ - 【LeetCode】Word Pattern
怪我咯
怪我咯 2017-04-17 13:05:28
0
1
702

我在 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;
    }
};

求指教。

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(1)
左手右手慢动作

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!