Skip to content

Instantly share code, notes, and snippets.

@ferbass
Last active August 2, 2022 13:10
Show Gist options
  • Save ferbass/2215c235debfc9852f04a8448c6e581e to your computer and use it in GitHub Desktop.
Save ferbass/2215c235debfc9852f04a8448c6e581e to your computer and use it in GitHub Desktop.
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;
}
};
# @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
@ferbass
Copy link
Author

ferbass commented Aug 2, 2022

https://leetcode.com/problems/palindrome-partitioning/submissions/

  • C++ Score

Runtime: 115 ms, faster than 94.60% of C++ online submissions for Palindrome Partitioning.
Memory Usage: 49.2 MB, less than 96.64% of C++ online submissions for Palindrome Partitioning.

  • Ruby Score

Runtime: 1909 ms, faster than 63.16% of Ruby online submissions for Palindrome Partitioning.
Memory Usage: 245.1 MB, less than 36.84% of Ruby online submissions for Palindrome Partitioning.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment