字符串可以。转换的地址值有哪些。

146 阅读1分钟
/**
 * 
 * @param str  字符串
 * @param length    字符串长度
 * @param index     当前的索引
 * @param remain    剩余的数量
 * @param path      路径
 * @param res       结果
 */
public static void dfs(String str, int length, int index, int remain, StringBuilder path, List<String> res) {

    if (remain == 0 && index == length) {
        res.add(path.toString());
        return;
    }

    if (remain < 0 || index == length) {
        return;
    }

    //从index+1往后凑出地址值
    for (int i = index + 1; i <= index + 3; i++) {
        if (i > length) {
            break;
        }
        String temp = str.substring(index, i);

        if (isRight(temp)) {
            path.append(temp);
            if (remain > 1) {
                path.append(".");
            }
            //深度优先遍历
            dfs(str, length, i, remain - 1, path, res);
            if (remain > 1) {
                path.deleteCharAt(path.length() - 1);
            }
            path.delete(path.length() - temp.length(), path.length());
        }
    }

}

/**
 * 字符串是否是合法的
 *
 * @param s
 * @return
 */
public static boolean isRight(String s) {
    int length = s.length();
    int value = Integer.valueOf(s);
    return length == 1 || length == 2 && (10 <= value) && (value <= 99) || length == 3 && (100 <= value) && (value <= 255);
}