当前位置:网站首页>2022.08.03_每日一题
2022.08.03_每日一题
2022-08-05 11:48:00 【诺.い】
93. 复原 IP 地址
题目描述
有效 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 '.' 分隔。
- 例如:
"0.1.2.201"和"192.168.1.1"是 有效 IP 地址,但是"0.011.255.245"、"192.168.1.312"和"[email protected]"是 无效 IP 地址。
给定一个只包含数字的字符串 s ,用以表示一个 IP 地址,返回所有可能的有效 IP 地址,这些地址可以通过在 s 中插入 '.' 来形成。你 不能 重新排序或删除 s 中的任何数字。你可以按 任何 顺序返回答案。
示例 1:
输入:s = “25525511135”
输出:[“255.255.11.135”,“255.255.111.35”]
示例 2:
输入:s = “0000”
输出:[“0.0.0.0”]
示例 3:
输入:s = “101023”
输出:[“1.0.10.23”,“1.0.102.3”,“10.1.0.23”,“10.10.2.3”,“101.0.2.3”]
提示:
1 <= s.length <= 20s仅由数字组成
coding
class Solution {
String s;
int len;
// cnt : 记录当前 '.' 的数量
int cnt = 0;
List<String> res;
public List<String> restoreIpAddresses(String s) {
this.s = s;
this.len = s.length();
this.res = new ArrayList<>();
// s 过长或过短
if(len < 4 || len > 12) {
return res;
}
dfs(0, new StringBuilder(len + 3));
return res;
}
// index : 下一个拼接字串的首字母索引
// sb : 记录当前已经符合条件的部分 ip
public void dfs(int index, StringBuilder sb) {
// 已经拥有 3 个 '.', 只需判断最后剩余的字串是否满足条件
// 若满足, 则直接计入结果, 否则直接结束方法
if (cnt == 3) {
if(isOK(index, len)){
sb.append(s.substring(index, len));
res.add(new String(sb));
sb.delete(index + cnt, len + 3);
}
return;
}
for (int i = 1; i < 4; i++) {
if (index + i <= len && isOK(index, index + i)) {
sb.append(s.substring(index, index + i));
sb.append('.');
cnt ++;
dfs(index + i, sb);
// 回溯
sb.delete(index + cnt - 1, index + i + cnt);
cnt --;
} else {
return;
}
}
}
// 判断子字符串是否符合条件
public boolean isOK(int l, int r) {
if(r - l < 1 || (r - l > 1 && (s.charAt(l) == '0' || Integer.parseInt(s.substring(l, r)) > 255))) {
return false;
}
return true;
}
}
边栏推荐
猜你喜欢

JS 从零手写实现一个call、apply方法

623. Add a row to a binary tree: Simple binary tree traversal problems

详细剖析 Redis 三种集群策略

2022 CCF International AIOps Challenge Finals and AIOps Seminar Registration Open

5G NR system messages

623. 在二叉树中增加一行 : 简单二叉树遍历运用题

Flink Yarn Per Job - 启动TM,向RM注册,RM分配solt

内存问题难定位,那是因为你没用ASAN

深度学习(四)分析问题与调参 理论部分

后缀自动机(SAM)——黑盒使用方案
随机推荐
基于NSQ搭建高可用分布式消息队列
使用Netty编写通用redis客户端(可指定服务器地址与端口号连接任意redis)
支持向量机SVM
el-menu箭头改为右下
Mathcad 15.0软件安装包下载及安装教程
普通二本毕业八年,京东就职两年、百度三年,分享大厂心得
Android development with Kotlin programming language II Conditional control
796. 子矩阵的和
澳洲站:电吹风AS/NZS 60335.2.23: 2017 安全标准测试
365 days challenge LeetCode1000 questions - Day 050 add a row to the binary tree binary tree
Gao Zelong attended the Boao Global Tourism Ecology Conference to talk about Metaverse and Future Network Technology
STM32H743IIT6学习笔记02——USART
Keras 模型多输出 loss weight metrics 设置
小红的aba子序列(离散化、二分、dp维护区间最短)
分布式事务解决方案
A woman is the most beautiful life in the world
UDP communication
知乎提问:中国是否还能实现伟大民族复兴
详细剖析 Redis 三种集群策略
关注微信公众号,自动登陆网站