其他分享
首页 > 其他分享> > LeetCode 0093 Restore IP Addresses

LeetCode 0093 Restore IP Addresses

作者:互联网

原题传送门

1. 题目描述

2. Solution 1

1、思路分析
3重循环把字符串s分成4个子串: s1, s2, s3, s4,通过函数isValid检查每个子串是否合法。
在isValid函数中,输入参数,s的长度超过3或者长度等于0是非法的;或者s的长度超过1,但是第1个字符为0也是非法的;或者s转换成int后,值大于255也是非法的。
2、代码实现

package Q0099.Q0093RestoreIPAddresses;

import java.util.ArrayList;
import java.util.List;

/*
   3-loop divides the string s into 4 substring: s1, s2, s3, s4. Check if each substring is valid.
   In isValid, strings whose length greater than 3 or equals to 0 is not valid; or if the string's length is longer
   than 1 and the first letter is '0' then it's invalid;
   or the string whose integer representation greater than 255 is invalid.
 */
public class Solution {
    public List<String> restoreIpAddresses(String s) {
        List<String> result = new ArrayList<String>();
        int len = s.length();
        for (int i = 1; i < 4 && i < len - 2; i++) {
            for (int j = i + 1; j < i + 4 && j < len - 1; j++) {
                for (int k = j + 1; k < j + 4 && k < len; k++) {
                    String s1 = s.substring(0, i);
                    String s2 = s.substring(i, j);
                    String s3 = s.substring(j, k);
                    String s4 = s.substring(k, len);
                    if (isValid(s1) && isValid(s2) && isValid(s3) && isValid(s4))
                        result.add(s1 + "." + s2 + "." + s3 + "." + s4);
                }
            }
        }
        return result;
    }

    public boolean isValid(String s) {
        return s.length() <= 3 &&
                s.length() != 0 &&
                (s.charAt(0) != '0' || s.length() <= 1) &&
                Integer.parseInt(s) <= 255;
    }
}

3、复杂度分析
时间复杂度:

标签:Restore,Addresses,segId,int,IP,segStart,isValid,0093,String
来源: https://www.cnblogs.com/junstat/p/16220341.html