[双指针] leetcode 1147 Longest Chunked Palindrome Decomposition

problem:https://leetcode.com/contest/weekly-contest-148/problems/longest-chunked-palindrome-decomposition/

        周赛题。首尾两个指针,检测前后字符串是否相等,如果相等则两个指针都移动到下一个匹配位置;不相等则继续在当前位置查找匹配。

class Solution {
public:
    int longestDecomposition(string text) {
        int i = 0;
        int j = text.size() - 1;
        int res = 0;
        while(i < j)
        {
            int old_i = i;
            while(true)
            {            
                if(i == j) return res + 1;
                if(text[i] == text[j])
                {
                    int size = i - old_i + 1;
                    int new_j = j - size + 1;
                    cout << text.substr(old_i, size) << " " << text.substr(new_j, size) << endl;
                    if(new_j <= i)
                    {
                        return res + 1;   
                    }
                    if(text.substr(old_i, size) != text.substr(new_j, size))
                    {
                        
                    }
                    else
                    {
                        j = new_j - 1;
                        i++;
                        res += 2;
                        break;
                    }
                }
                i++;
            }
        }
        if(i == j) return res + 1;
        return res;
    }
};

 

posted @ 2019-08-04 13:25  fish1996  阅读(251)  评论(0)    收藏  举报