[Leetcode] palindrome partitioning

Source: Internet
Author: User

Given a stringS, PartitionSSuch that every substring of the partition is a palindrome.

Return all possible palindrome partitioningS.

For example, givenS="aab",
Return

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

 

Solution:

DFS

 1 class Solution { 2     private: 3             vector<vector<string> >   m_res; 4     public: 5         vector<vector<string> > partition(string s) 6         { 7             size_t size = s.size(); 8             if(size == 0) 9                 return m_res;10 11             vector<string> str;12             dfs(s, 0, size - 1, str);13             return m_res;14         }15 16         void dfs(string s, size_t begin, size_t end, vector<string>& str)17         {18             if(begin > end)19             {20                 m_res.push_back(str);21                 return;22             }23 24             for(size_t i = begin; i<=  end; i++)25             {26                 if(isPalindrome(s, begin, i))27                 {28                     str.push_back(s.substr(begin, i-begin + 1));29                     dfs(s, i+1, end, str);30                     str.pop_back();31                 }32             }33         }34 35         bool isPalindrome(string s, size_t begin, size_t end)36         {37             if(begin == end)38                 return true;39             while(begin <= end)40             {41                 if(s[begin] == s[end])42                 {43                     begin++;44                     end --;45                 }46                 else47                     return false;48             }49             return true;50         }51 };

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.