<分区>
关于字符串的紧凑输出。
示例 1
Input : boooooob
Output : bob
例子2
Input : boobaabbiibbuuuuub
Output : bobabibub
谁能帮帮我?
我卡住了,谢谢。
<分区>
关于字符串的紧凑输出。
示例 1
Input : boooooob
Output : bob
例子2
Input : boobaabbiibbuuuuub
Output : bobabibub
谁能帮帮我?
我卡住了,谢谢。
最佳答案
这可以通过使用正则表达式(\\w)\\1+
来解决
public class RemoveReplicateLetter {
public static void main(String[] args) {
//For input: boooooob
System.out.println(removeReplicateLetter("boooooob"));
//For input: boobaabbiibbuuuuub
System.out.println(removeReplicateLetter("boobaabbiibbuuuuub"));
}
public static String removeReplicateLetter(String word) {
/*
REGEX:
(\\w)\\1+
- \\w : matches any word character (letter, digit, or underscore)
- \\1+ : matches whatever was in the first set of parentheses, one or more times.
*/
return word.replaceAll("(\\w)\\1+", "$1");
//Here $1 means return letter with match in word by regex.
}
}
输出:
bob
bobabibub
关于Java程序,字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33820963/