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)

Solution:

注意这里if(tmp < 256 && tmp.toString().equals(s.substring(pos, pos + j)))

如果不加tmp.toString().equals(s.substring(pos, pos + j)), 则可能会出现001 这种情况, 即高位为0.

 1 public class Solution {

 2     ArrayList<String> result = null;

 3     public ArrayList<String> restoreIpAddresses(String s) {

 4         // IMPORTANT: Please reset any member data you declared, as

 5         // the same Solution instance will be reused for each test case.

 6         result = new ArrayList<String>();

 7         getAddress(s, 0, 4, new StringBuffer());

 8         return result;

 9     }

10     public void getAddress(String s, int pos, int num, StringBuffer sb){

11         if(num == 0 || pos == s.length()){

12             if(pos == s.length() && num == 0){

13                 result.add(sb.substring(0, sb.length() - 1));

14             }

15             return;

16         }

17         for(int j = 1; j < 4 && pos + j <= s.length(); j ++){

18             Integer tmp = Integer.valueOf(s.substring(pos, pos + j));

19             if(tmp < 256 && tmp.toString().equals(s.substring(pos, pos + j))){

20                 sb.append(s.substring(pos, pos + j));

21                 sb.append(".");

22                 getAddress(s, pos + j, num - 1, sb);

23                 sb.delete(sb.length() - j - 1, sb.length());

24             }

25         }

26     }

27 }

 

你可能感兴趣的:(store)