Palindrome Pairs

weixin_34007291發表於2017-05-02

題目來源
給一個字串陣列,求能組成迴文串的兩個元素的。
就是比較煩,但是倒不是很難。
程式碼如下:

class Solution {
public:
    vector<vector<int>> palindromePairs(vector<string>& words) {
        int len = words.size();
        unordered_map<string, int> maps;
        vector<vector<int>> res;
        for (int i=0; i<len; i++) {
            if (words[i] == "")
                continue;
            maps[words[i]] = i;
        }
        for (int i=0; i<len; i++) {
            int wordLen = words[i].size();
            if (wordLen == 0)
                for (int j=0; j<len; j++) {
                    if (i != j && isPalindrome(words[j])) {
                        res.push_back(vector<int>{i, j});
                        res.push_back(vector<int>{j, i});
                    }   
                }
            for (int j=wordLen; j>=1; j--) {
                string left = words[i].substr(0, j);
                string right = words[i].substr(j);
                bool isleft = isPalindrome(left);
                bool isright = isPalindrome(right);
                reverse(left.begin(), left.end());
                reverse(right.begin(), right.end());
                if (isright && maps.count(left) != 0 && maps[left] != i) {
                    vector<int> pair{i, maps[left]};
                        res.push_back(pair);
                }
                if (isleft && maps.count(right) != 0 && maps[right] != i) {
                    vector<int> pair{maps[right], i};
                        res.push_back(pair);
                }
            }
        }
        return res;
    }
    
    bool isPalindrome(string &str)
    {
        if (str == "")
            return true;
        int p1 = 0, p2 = str.size() - 1;
        while (p1 < p2) {
            if (str[p1] != str[p2])
                return false;
            p1++;
            p2--;
        }
        return true;
    }
};

相關文章