Linecode 680 Split String, lincodesplit
Split String
- Description
- Notes
- Data
- Evaluation
Give a string, you can choose to split the string after one character or two adjacent characters, and make the string to be composed of only one character or two characters. Output all possible results.
Have you ever encountered this question during a real interview? Yes
Example
Given the string"123"
Return[["1","2","3"],["12","3"],["1","23"]]
At the beginning, I thought about the first point, but later I found that it was not necessary. Now I feel that void can be used with void. It is strange that too many return values are not dizzy.
1. We can see that the function returned type given by the question is a nested vector, so it is easy to think of another solution function and the return type is vector.
2. The problem of the backtracking method must be restored to the site. The problem is how to restore the site.
3. Consider When to insert a nested vector and insert conditions.
4. note how to operate when s. size () = 0
Below is the code that has not been optimized again. If there is an error or improvement, please point it out.
class Solution {public: /* * @param : a string to be split * @return: all possible split string array */ vector <string> a; vector<vector<string> > ans; void back(int t,int n,string &s) { if(!s.size()) { ans.push_back(a); return ; } if(t>=s.size()) return ; else{ if(n==1){ string c=""; c=c+s[t]; a.push_back(c); if(t+1==s.size()){ ans.push_back(a); } t++; back(t,1,s); t++; back(t,2,s); t-=2; a.erase(a.end()-1); } else{ string c=""; c=c+s[t-1]+s[t]; a.push_back(c); if(t+1==s.size()){ ans.push_back(a); } t++; back(t,1,s); t++; back(t,2,s); t-=2; a.erase(a.end()-1); } } return ; } vector<vector<string> > splitString(string& s) { // write your code here back(0,1,s); if(s.size()>1) back(1,2,s); return ans; }};