Restore IP Addresses
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)
思路:典型的DFS题目,确定好下一步状态,已经结束条件。
- ArrayList<String> res = new ArrayList<String>();
- StringBuffer cur = new StringBuffer();
- boolean isValid(String s1) {
- if(s1.charAt(0)=='0') return s1.compareTo("0") == 0; //不能用==来判断,完全相等,包含地址
- if(Integer.parseInt(s1)>255 || Integer.parseInt(s1) < 0) return false;
- return true;
- }
- void helper(String s,int start,int index) {
- if(index == 4) { //结束条件
- if(start == s.length()) {
- res.add(new String(cur));
- }
- return;
- }
- for(int i=1;i<=3;i++) {
- if(start+i-1>=s.length()) break;
- String str = s.substring(start,start+i);
- if(isValid(str)) {
- int size = cur.length();
- String tmp ="";
- if(start!=0) {
- tmp = "." + str;
- } else {
- tmp = str;
- }
- cur.append(tmp);
- helper(s,start+i,index+1);
- cur = cur.delete(size,cur.length()); //恢复前一个状态,StringBuffer有些捉急
- }
- }
- }
- public List<String> restoreIpAddresses(String s) {
- int s1 = s.length();
- if(s==null || s1==0) return res;
- helper(s,0,0);
- return res;
- }
C++代码:
- vector<string> res;
- bool isValid(string &s,int start,int end) {
- string tmp = s.substr(start,end-start+1);
- if(tmp.at(0)=='0') return tmp=="0";
- int k=stoi(tmp);
- return k<=255 && k>=0;
- }
- void restoreIpAddressesHelper(string &s,string &cur,int count,int start) {
- if(count==4) {
- if(start==s.size()) {
- res.push_back(cur);
- }
- return;
- }
- for(int i=start;i<start+3&&i<s.size();i++) {
- if(isValid(s,start,i)) {
- int tmp=cur.size();
- cur+=s.substr(start,i-start+1);
- if(count<3) cur+='.';
- restoreIpAddressesHelper(s,cur,count+1,i+1);
- cur.resize(tmp);
- }
- }
- }
- vector<string> restoreIpAddresses(string s) {
- if(s.size()==0) return res;
- string cur;
- restoreIpAddressesHelper(s,cur,0,0);
- return res;
- }