131. 分割回文串

✅做题思路or感想

这题的主题有两个:分割字符串检查是否回文

难点在于第一点,这里用startIndex作为子串开始的地方,i作为子串结束的地方,用s.substr(startIndex, i - startIndex + 1)来分割出子串

递归单层逻辑就是判断子串是否回文,如果回文,则加入vector<string>中,否则continue

class Solution {
public:
    vector<vector<string>>result;
    vector<string>vec;
    //用双指针法来判断是否回文
    bool isGood(string s, int left, int right) {
        while (left <= right) {
            if (s[left] != s[right])return false;
            left++;
            right--;
        }
        return true;
    }
    void dfs (string s, int startIndex) {
        //当子串初始点大于主串末尾时,就结束递归
        if (startIndex >= s.size()) {
            result.push_back(vec);
            return;
        }
        for (int i = startIndex; i < s.size(); i++) {
            if (isGood(s, startIndex, i)) {
                string str = s.substr(startIndex, i - startIndex + 1);
                vec.push_back(str);
                dfs(s, i + 1);
                vec.pop_back();//回溯
            } else continue;
        }
    }
    vector<vector<string>> partition(string s) {
        dfs(s, 0);
        return result;
    }
};
posted @ 2022-04-02 17:29  北原春希  阅读(50)  评论(0)    收藏  举报