gpt4 book ai didi

java - 在字符串中存储和打印连续字符?

转载 作者:行者123 更新时间:2023-12-04 07:58:44 25 4
gpt4 key购买 nike

任务是将连续字符存储在列表中。带有输入/输出的 Main 如下所示:

public static void main(String[] args) {
List<String> blocks = blocks("Hello faaantastic world");
System.out.println(blocks); // => ["ll", "aaa"]
System.out.println(blocks("aaabccdeeeefaaa")); // => ["aaa", "cc", "eeee", "aaa"]
System.out.println(blocks("This is an example")); // => []
System.out.println(blocks("Another example ...")); // => [" ", "..."]
System.out.println(blocks("")); // => []
我的方法是这样的:
public static LinkedList<String> blocks(String s) {
LinkedList<String> list = new LinkedList<>();
String word = "";

for(char c : s.toCharArray()) {
if (c == ??) {

}
}

return list;
String 字用于存储连续的字母。我找到了 toCharArray,用于拆分字符串的每个字符。但是我对 if 块有问题。如果我做 c == c+1 来检查 I 和 I 的以下字符,它不起作用......我不知道如何解决这个问题。有人能帮我吗?现在试图解决它2天...

最佳答案

在这种情况下,最好使用 String::charAt方法来检索输入字符串中的字符并将它们与前一个字符进行比较。

public static LinkedList<String> blocks(String s) {
LinkedList<String> list = new LinkedList<>();

String word = "" + s.charAt(0);

for(int i = 1, n = s.length(); i < n; i++) {
if (s.charAt(i) == s.charAt(i - 1)) {
word += s.charAt(i);
} else {
if (word.length() > 1) {
list.add(word);
}
word = "" + s.charAt(i);
}
}
if (word.length() > 1) {
list.add(word);
}

return list;
}
测试
System.out.println(blocks("Hello faaantastic worlddd"));
输出
[ll, aaa, ddd]

使用正则表达式可以找到更短的解决方案来查找重复字符 (.)\1+ :
public static List<String> findConsecutive(String s) {
return Pattern.compile("(.)\\1+").matcher(s).results() // Stream<MatchResult>
.map(mr -> mr.group(0)) // 0 group contains repeated characters
.collect(Collectors.toList());
}
测试
System.out.println(findConsecutive("Hello   faaantastic worlddd"));
输出
[ll,    , aaa, ddd]

关于java - 在字符串中存储和打印连续字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66572817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com