题解 | #所有的回文子串I#
所有的回文子串I
https://www.nowcoder.com/practice/37fd2d1996c6416fa76e1aa46e352141
知识点:
回溯/递归/回文/DFS
分析:
需要检查是否满足回文,回文的判断很简单了,写一个函数备用即可。
在DFS中,设置一个索引 ```u``` 来依次选择开始遍历的起始位置,索引 u 大于等于这个字符串的长度了,就是终止条件,把path装如结果中即可。
具体的,遍历中,判断是否满足回文,通过substr函数截取字符串,将满足回文的子串装入path中,并且进行回溯,满足了装,知道不满足就不在加了,所以不满足回文的话 直接继续循环,continue,再进行回溯的过程。
编程语言:
C++
完整代码:
vector<string> path;
vector<vector<string> > res;
bool isp(string s1,int st,int ed){
int i = st;
int j = ed;
while(i < j){
if(s1[i++] != s1[j--]) return false;
}
return true;
}
void dfs(string s,int u){
if(u >= s.size()){res.push_back(path);return;}
for(int i = u;i<s.size();i++){
if(isp(s, u, i)){
string str = s.substr(u,i-u+1);
path.push_back(str);
}else continue;
dfs(s,i+1);
path.pop_back();
}
}
vector<vector<string> > partition(string s) {
dfs(s,0);
return res;
}

