一、使用场景
包含但是不局限于以下场景使用。
- 字符串中连续相同字符。例如,“abbccc”判断最大连续相同字符数。
- 字符串中包含多少个单词或者数值。例如,“a, bb, ccc”,“1, 22, 33”。
二、通用示例
1.字符串中连续相同字符
代码如下(示例):
public static void main(String[] args) {
String s = "abbccc";
int max = 0;
for (int i = 0; i < s.length() - 1;i++) {
int j = i;
int count = 1;
while (j < s.length() - 1 && s.charAt(j) == s.charAt(j+1)) {
count++;
j++;
}
i = j;
max = Math.max(max, count);
}
System.out.println(max);
}
2.字符串中包含多少个单词或者数值
代码如下(示例):
public static void main(String[] args) {
String s = "a,bb,ccc";
List<String> list = new ArrayList<>();
for (int i = 0; i < s.length(); i++) {
int j = i;
StringBuilder sb = new StringBuilder();
while (j < s.length() && s.charAt(j) >= 'a' && s.charAt(j) <= 'z') {
sb.append(s.charAt(j));
j++;
}
i = j;
list.add(sb.toString());
}
System.out.println(list);
}
三、要点
- 第一次循环中 i++ 的使用。判断是否需要加上。
- 在 while 的循环中判断 j++ 的使用。判断使用的位置是否正确。
- 在 while 的循环中判断 j < s.length() 的使用,在循环判断的最后因为没有相应的字符会越界。
- 在循环的最后 i=j 的使用。判断使用的位置是否正确,判断是否需要改为 i=j+1。
四、力扣相关示例(不定期更新)
以上示例只是用于展示使用方法,更丰富的例子可以参考以下力扣的题目。
如果刷题时遇到相似的示例,我会更新示例列表。
385. 迷你语法分析器:示例,“[123,[456,[789]]]”
388. 文件的最长绝对路径:示例,“file1.txt\nfile2.txt\nlongfile.txt”
824. 山羊拉丁文:示例,“I speak Goat Latin”
819. 最常见的单词:示例,“Bob hit a ball, the hit BALL flew far after it was hit.”