leetcode string

1. palindrome-partitioning

解法: 因为需要输出所有的可行解,所以采用深度优先遍历(回溯法)。输出最佳解的题目一般可以使用动态规划。

 1 class Solution {
 2 public:  3 vector<vector<string>> partition(string s) {  4 vector<vector<string> > res;  5 vector<string> cur;  6  dfs(s,cur,res);  7 return res;  8  }  9 bool isPalindrome(string s){ 10 return s==string(s.rbegin(),s.rend()); 11  } 12 void dfs(string s, vector<string> &cur, vector<vector<string> > &res){ 13 if(s==""){ 14  res.push_back(cur); 15 return; 16  } 17 for(int i=1;i<=s.length();++i){ 18 string sub = s.substr(0,i); 19 if(isPalindrome(sub)){ 20  cur.push_back(sub); 21 dfs(s.substr(i,s.length()-i),cur,res); 22  cur.pop_back(); 23  } 24  } 25  } 26 };

2. simplify-path

知识点:

https://www.cnblogs.com/propheteia/archive/2012/07/12/2588225.html

stringstream的基本用法参考以上链接。

 1 class Solution {
 2     public:
 3         //中间是"."的情况直接去掉,是".."时删掉它上面挨着的一个路径,
 4         //如果是空的话返回"/",如果有多个"/"只保留一个。
 5         string simplifyPath(string path) {
 6             vector<string> res;
 7             stringstream ss(path);
 8             string sub;
 9             while(getline(ss,sub,'/')) {
10                 if(sub=="." || sub=="")
11                     continue;
12                 else if(sub==".."&&res.size()) {
13                     res.pop_back();
14                 } else if(sub!="..") {
15                     res.push_back(sub);
16                 }
17 
18             }
19             string result;
20             for(string s:res) {
21                 result+="/"+s;
22             }
23             return res.empty() ? "/":result;
24         }
25 };

猜你喜欢

转载自www.cnblogs.com/xctcherry/p/8995885.html
今日推荐