zoukankan      html  css  js  c++  java
  • [leetcode]Restore IP Addresses

    DFS的遍历。里面的关键是两个:1.使用了合理的数据结构,用ArrayList<String>来存每一段;2.后来发现一个条件是,除了‘0’以外不能有以‘0’开头的段;

    我看有的人判断比255小是先转化为数字再判断,比我这个字符串的简单。

    public class Solution {
        ArrayList<String> result = new ArrayList<String>();
        ArrayList<String> section = new ArrayList<String>();
        public ArrayList<String> restoreIpAddresses(String s) {
            result.clear();
            section.clear();
            dfs(s, 0, 0);
            return result;
        }
        
        private void dfs(String s, int pos, int depth)
        {
            if (depth == 4)
            {
                int len = 0;
                for (int i = 0; i < 4; i++)
                {
                    len += section.get(i).length();
                }
                if (len != s.length()) return;
                else
                {
                    result.add(section.get(0) + '.' +
                                section.get(1) + '.' +
                                section.get(2) + '.' +
                                section.get(3));
                }
            }
            else
            {
                if (pos < s.length())
                {
                    section.add(s.substring(pos, pos+1));
                    dfs(s, pos+1, depth+1);
                    section.remove(section.size()-1);
                }
                if (pos + 1 < s.length() && s.charAt(pos) != '0')
                {
                    section.add(s.substring(pos, pos+2));
                    dfs(s, pos+2, depth+1);
                    section.remove(section.size()-1);
                }
                if (pos + 2 < s.length() && isValid(s, pos))
                {
                    section.add(s.substring(pos, pos+3));
                    dfs(s, pos+3, depth+1);
                    section.remove(section.size()-1);
                }
            }
        }
        
        private boolean isValid(String s, int pos)
        {
            if (s.charAt(pos) == '0') return false;
            if (s.charAt(pos) > '2') return false;
            if (s.charAt(pos) < '2') return true;
            // s[pos] == '2'
            if (s.charAt(pos+1) > '5') return false;
            if (s.charAt(pos+1) < '5') return true;
            // s[pos+1] == '5'
            return (s.charAt(pos+2) <= '5');
        }
    }
    

      

  • 相关阅读:
    什么是垃圾回收
    Oracle GoldenGate学习之Goldengate介绍
    JVM虚拟机选项:Xms Xmx PermSize MaxPermSize区别
    查看linux系统版本命令
    Case when 的用法,简单Case函数
    case when then else end
    ORACLE视图添加备注
    修改 tomcat 内存
    Linux 内存机制详解宝典
    oracle正则表达式regexp_like的用法详解
  • 原文地址:https://www.cnblogs.com/lautsie/p/3330781.html
Copyright © 2011-2022 走看看