• 【LeetCode】131. Palindrome Partitioning


    Palindrome Partitioning

    Given a string s, partition s such that every substring of the partition is a palindrome.

    Return all possible palindrome partitioning of s.

    For example, given s = "aab",
    Return

      [
        ["aa","b"],
        ["a","a","b"]
      ]

    空间换时间。

    使用二维数组isPalin记录每个子串是否为回文串。

    然后递归来做。可以看做深度优先搜索。

    class Solution {
    public:
        vector<vector<bool> > isPalin;  // isPalin[i][j]==true means s[i,...,j] is palindrome
        void buildMap(string s)
        {
            int n = s.size();
            isPalin.resize(n, vector<bool>(n, false));
            for(int i = 0; i < n; i ++)
                isPalin[i][i] = true;
            for(int i = n-1; i >= 0; i --)
            {
                for(int j = i+1; j < n; j ++)
                {
                    if(s[i] == s[j])
                    {
                        if(j == i+1 || isPalin[i+1][j-1] == true)
                            isPalin[i][j] = true;
                    }
                }
            }
        }
        vector<vector<string>> partition(string s) {
            buildMap(s);
            vector<vector<string> > ret;
            vector<string> cur;
            Helper(ret, cur, s, 0);
            return ret;
        }
        void Helper(vector<vector<string> >& ret, vector<string> cur, string s, int offset)
        {
            if(s == "")
                ret.push_back(cur);
            for(int i = 0; i < s.size(); i ++)
            {
                if(isPalin[offset+0][offset+i] == true)
                {
                    cur.push_back(s.substr(0, i+1));    //palin prefix
                    Helper(ret, cur, s.substr(i+1), offset+i+1);
                    cur.pop_back();
                }
            }
        }
    };

  • 相关阅读:
    jmeter测试get post 笔记
    Fiddler发送get post测试 笔记
    jmeter json乱码
    IDEA+selenium3+火狐/谷歌驱动 JAVA初步环境搭建 笔记
    java源代码
    java测试
    考试感受
    周进度总结
    周进度总结
    周进度总结
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4121762.html
Copyright © 2020-2023  润新知