欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

原创牛客网算法—名企高频面试题143题(16)

程序员文章站 2022-03-06 19:12:58
93. 复原IP地址class Solution { List res = new ArrayList<>(); public List restoreIpAddresses(String s) { List segment = new ArrayList<>(); //开始搜索 dfs(s, 0, segment);...

93. 复原IP地址

class Solution {
    List<String> res = new ArrayList<>();
    public List<String> restoreIpAddresses(String s) {
         List<String> segment = new ArrayList<>();
        //开始搜索
        dfs(s, 0, segment);
        return res;
    }
        private void dfs(String s, int start, List<String> segment) {
        if (start == s.length()) {
            if (segment.size() == 4) {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < segment.size(); i++) {
                    sb.append(segment.get(i));
                    if (i != segment.size() - 1) sb.append('.');
                }
                res.add(sb.toString());
            }
            return;
        } else {
            if (segment.size() >= 4) return;
            for (int i = start; i < s.length() && i < start + 3; i++) {
                String str = s.substring(start, i + 1);
                if (str.charAt(0) == '0' && str.length() > 1) break;
                int num = Integer.parseInt(str);
                if (num >= 0 && num <= 255) {
                    segment.add(str);
                    dfs(s, i + 1, segment);
                    segment.remove(segment.size() - 1);
                } else {
                    break;
                }
            }
        }
    }

}

468. 验证IP地址

 

本文地址:https://blog.csdn.net/weixin_41605937/article/details/111943014