Sunday, January 26, 2014

Restore IP Addresses LeetCode

这个题,在我写了无数次的DFS之后,还是卡住了,这个题容易出现bug的地方很多。

比如终止条件有三种要想到,太长太短或者是正好找到。
第二个问题是,当一个字段开头为0的时候,直接跳到下一个字段。
第三个问题是,在储存的时候,会在后面多加一个点要去掉,并且存之前判断是否有重复。
public ArrayList<String> restoreIpAddresses(String s) {
        ArrayList<String> result = new ArrayList<String>();
        if (s==null || s.length() < 4) return result;
        String ip = "";
        generate(s, 0, 0, result, ip);
        return result;
    }
 
    public void generate(String s, int start, int depth, ArrayList<String> result, String ip){
        int MAX_DEPTH = 4;
        // there are three conditions to stop the DFS
        // too long
        if (s.length() - start > (MAX_DEPTH - depth) * 3) return ;
        // too short
        if (s.length() - start < MAX_DEPTH - depth) return;
        //found one possible solution
        if (depth == 4){
            //remove the "."
            ip = ip.substring(0, ip.length() - 1);
            if (!result.contains(ip)) result.add(ip);
            return;
        }
        //update every depth
        int num = 0;
        for (int i = start; i < Math.min(start + 3, s.length()); i++){
            num = num*10 + (s.charAt(i) - '0');
         
            if (num <=255){
                generate(s, i+1, depth+1, result, ip + num + ".");
            }
            //if this depth start with 0, then we go to the next depth
            if (num == 0) break;
        }
    }

Previous solution is not clear since we did not make it as specific as possible.
DFS is key function
isValid is checking each small string is valid or not.

public List<String> restoreIpAddresses(String s) {
        List<String> result = new ArrayList<String>();
        if (s.length() < 4 || s.length() > 12) return result;
        dfs(result, "" ,s ,0);
        return result;
    }
   
    private void dfs(List<String> result, String currString, String s, int count) {
        if (count == 3 && isValid(s)) {
            result.add(currString+s);
            return;
        }
        for (int i=1; i<4 && i <s.length();i++) {
            String tempString = s.substring(0,i);
            if (isValid(tempString)) {
                dfs(result, currString+tempString+".", s.substring(i), count+1);
            }
        }
    }
   
    private boolean isValid(String s) {
        if (s.charAt(0) == '0') return s.length() == 1;
        int value = Integer.parseInt(s);
        return value>=0 && value<=255;
    }

No comments:

Post a Comment