题解 | #数字字符串转化成IP地址#

数字字符串转化成IP地址

http://www.nowcoder.com/practice/ce73540d47374dbe85b3125f57727e1e



public class Solution {
    /**
     * 
     * @param s string字符串 
     * @return string字符串ArrayList
     */
    ArrayList<String> ans = new ArrayList<>();
    public ArrayList<String> restoreIpAddresses (String s) {
        // write code here
        dfs(s, 0, new StringBuffer(), 0);

        return ans;
    }

    /**
     *
     * @param sb
     * @param begin 下一个遍历开始的位置,begin= sb.length为最右点
     * @param stringBuffer 记录已经分好的ip
     * @param count 记录位数
     */
    public void dfs(String sb, int begin, StringBuffer stringBuffer, int count) {
        if (count > 4 || begin > sb.length()) {
            return;
        }
        if (count == 4 && begin < sb.length() - 1) {
            return;
        }
        if (count == 4 && begin == sb.length()) {
            ans.add(stringBuffer.toString().substring(1));
            return;
        }

        for (int i = 1; i <= 3; i++) {
            if (begin + i > sb.length()) {
                return;
            }
            String substring = sb.substring(begin, i + begin);
            int n = Integer.parseInt(substring);
            if (n < 0 || n > 255 || (substring.length() >= 2 && substring.charAt(0) == '0')) {
                return;
            }
            StringBuffer append = new StringBuffer(stringBuffer).append(".").append(n);
            dfs(sb, begin + i, append, count + 1);
        }
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
评论
1
收藏
分享
牛客网
牛客企业服务