Last active
August 2, 2022 13:10
-
-
Save ferbass/2215c235debfc9852f04a8448c6e581e to your computer and use it in GitHub Desktop.
[Leetcode] 131. Palindrome Partitioning https://leetcode.com/problems/palindrome-partitioning/submissions/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<vector<string>> partition(string s) { | |
vector<vector<string>> result; | |
vector<string> part; | |
dfs(0, s, part, result); | |
return result; | |
} | |
void dfs(int i, string& s, vector<string>& part, vector<vector<string>>& result){ | |
if(i>=s.size()){ | |
result.push_back(part); | |
return; | |
} | |
for(int j = 1; (j+i) <= s.size(); j++){ | |
string str = s.substr(i,j); | |
if(isPalindrome(str)){ | |
part.push_back(str); | |
dfs(i+j, s, part, result); | |
part.pop_back(); | |
} | |
} | |
} | |
bool isPalindrome(string& s){ | |
int l = 0, r = s.size() - 1; | |
while(l < r){ | |
if(s[l] != s[r]) return false; | |
l++; | |
r--; | |
} | |
return true; | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# @param {String} s | |
# @return {String[][]} | |
def partition(s) | |
return [[s]] if s.length == 1 | |
result = [] | |
dfs(0, s, [], result) | |
return result | |
end | |
def dfs(i, s, part, result) | |
if i >= s.length | |
result<<part.clone | |
return | |
end | |
for j in i..s.length | |
if isPalindrome?(s, i, j) | |
part<<s[i..j] | |
dfs(j+1, s, part, result) | |
part.pop | |
end | |
end | |
end | |
def isPalindrome?(s, l, r) | |
while l < r | |
return false if s[l] != s[r] | |
l, r = l+1, r-1 | |
end | |
return true | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://leetcode.com/problems/palindrome-partitioning/submissions/