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

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param s string字符串
     * @return string字符串ArrayList
     */
    public ArrayList<String> restoreIpAddresses (String s) {
        ArrayList<String> arrayList  = new ArrayList<>();
        if (s.length() < 4) {
            return arrayList;
        }
        // write code here
        dealIpStr(s, 0, 0, new LinkedList<>(), arrayList);
        return arrayList;
    }

        public void dealIpStr(String s, int index,Integer count, LinkedList<String> list,ArrayList<String> arrayList) {
        if (count >= 3) {
            if (index<= s.length()-1) {
                String last = s.substring(index, s.length());
                  if (last.length() > 1&& last.startsWith("0")) {
                    return;
                }
                Integer lastI = new Integer(last);

                if ( lastI>=0 && lastI <= 255) {
                    StringBuilder builder = new StringBuilder();
                    for (String i : list) {
                        builder.append(i);
                        builder.append(".");
                    }
                    builder.append(lastI);
                    arrayList.add(builder.toString());
                }
            }
            return;
        }
        for (int i=1;i<=3;i++) {

            if ( index + i > s.length() ) {
                return;
            }


            String sub = s.substring(index, index + i);

            if (sub.length() > 1 && sub.startsWith("0")) {
                return;
            }

            if (index+i < s.length() &&  sub != "" &&  new Integer(sub) >= 0 && new Integer(sub)<= 255) {
                list.add(sub);
                dealIpStr(s,index+i,count+1,list,arrayList);
                list.removeLast();
            }
        }
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务