当前位置:网站首页>力扣今日题1108. IP 地址无效化
力扣今日题1108. IP 地址无效化
2022-06-21 17:48:00 【抗争的小青年】
1108. IP 地址无效化
难度是简单。不错,又可以增强信心了!
看题干,用一个字符串替换另一个字符串,涉及到字符串的替换和拼接,用StringBuilder吧!为了便于书写,我改了函数签名。
class Solution {
public String defangIPaddr(String ad) {
//创建一个StringBulider的help对象,来帮助我们保存结果
StringBuilder help = new StringBuilder();
//对字符串遍历,查找题目规定的字符“.”,并将"."替换成"[.]"
for(int i = 0;i < ad.length(); i++){
if(ad.charAt(i) == '.'){
help.append("[.]");
//使用continue来优化遍历
continue;
}
//不是规定字符就直接添加到帮助字符串中
help.append(ad.charAt(i));
}
//将对象转换成字符串
return help.toString();
}
}

一行代码版本java
class Solution {
public String defangIPaddr(String ad) {
return ad.replace(".","[.]");
}
}

一行代码版本JavaScript
/**
* @param {string} address
* @return {string}
*/
var defangIPaddr = function(ad) {
return ad.replaceAll(".","[.]")
};
注意:
charAt(int index)方法是一个能够用来检索特定索引下的字符的String实例的方法。
charAt()方法返回指定索引位置的char值。索引范围为0~length()-1,如: str.charAt(0)检索str中的第一个字符,str.charAt(str.length()-1)检索最后一个字符。
Java入门第82课——StringBuilder的append方法
字符串的replace方法
JavaScript中的replace方法,只会替换第一个字符,所有这里用的replaceAll方法。
边栏推荐
- El expression
- # bash 的 try catch
- Leetcode (210) - Schedule II
- 50位中国女性科学家入选2022福布斯
- Leetcode(210)——课程表 II
- I/0多路转接之select
- Enabling developers of shengteng scientific research innovation enabling program Huawei computing provides three dimensional support
- With mitmdump, don't throw it away, Charles
- Servlet specification (I)
- In air operation, only distance mapping is used to robustly locate occluded targets (ral2022)
猜你喜欢
随机推荐
Ropsten测试网的水龙头上得到一些ETH
El expression
牛客网:归并两个有序的数组
一篇文章彻底学会画数据流图
canvas动态背景文本发光js特效
[HCTF 2018]WarmUp
Must the database primary key be self incremented? What scenarios do not suggest self augmentation?
Collaborative filtering
Start! Alibaba programming summer 2022
From "village run enterprise" to "ten billion group", why did red star industry complete the "butterfly transformation"?
华为鸿蒙认证测试题,你能答对几道?
Teachers, Oracle CDC encounters a DML statement that cannot be parsed because a field in this statement is a special spatial and geographical bit
外资上演“胜利大逃亡”、内资接盘,新东方在线“方”了?
数据库主键一定要自增吗?有哪些场景不建议自增?
Day11QPainter2021-09-26
这篇寒门博士论文致谢火了:回首望过去,可怜无数山
WWDC22 多媒体特性汇总
GOF mode-03-behavioral mode (bottom)
Servlet学习(二)
Make interface automation test flexible








