Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given "25525511135"
,
return ["255.255.11.135", "255.255.111.35"]
. (Order does not matter)
class Solution { public: vector<string> restoreIpAddresses(string s) { int l = s.length(), c, t, ls, idx, i; vector<string> ans; if(l < 4 || l > 12) return ans; string str; queue<string> q; q.push(str); queue<int> pntq; //number of points pntq.push(0); while(!q.empty()) { str = q.front(); q.pop(); c = pntq.front(); pntq.pop(); ls = str.length(); for(i = 0, t = 0; i < 3; i++) { idx = ls - c + i; t = t * 10 + s[idx] - '0'; if(t > 255) break; if(l-idx-1 >= 3-c && l-idx-1 <= 3*(3-c)) { string ts = str + s.substr(ls-c, i+1); if(c < 3) { ts += "."; q.push(ts); pntq.push(c+1); } else { ans.push_back(ts); } } if(0 == i && '0' == s[idx]) //注意不能出现010之类以0开头的子串 break; } } return ans; } };
注意不能出现010之类以0开头的子串