[Leetcode] palindrome partitioning

Source: Internet
Author: User

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",

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


To list all possibilities, go directly to DFS


class Solution {public:    vector<vector<string> > res;        vector<vector<string>> partition(string s) {        vector<string> partitions;        dfs(partitions, s, 0);                return res;    }        void dfs(vector<string> partitions, string &s, int idx) {        if (idx >= s.size()) {            if (partitions.size() > 0) {                res.push_back(partitions);            }            return;        }                for (int i = idx; i < s.size(); ++i) {            string cur = s.substr(idx, i - idx + 1);            if (isPalindrome(cur)) {                partitions.push_back(cur);                dfs(partitions, s, i + 1);                partitions.pop_back();            }        }                return;    }        bool isPalindrome(string s) {        int len = s.size();        if (len <= 1) return true;                int left = 0;        int right = len - 1;        while (left < right) {            if (s[left] != s[right]) return false;            ++left;            --right;        }        return true;    }};

[Leetcode] palindrome partitioning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.