Java程序,字符串

标签 java string algorithm

<分区>

关于字符串的紧凑输出。

示例 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/

相关文章:

java - 我想获得特定月份的周数

java - 在 CardLayout 类之间传递数据

Java deleteCharAt 函数

javascript - 如何替换字符串中的 "is"等单词,而不影响 "Pakistani"|节点js

algorithm - B-Tree - 为什么不能有一个节点的键数是偶数?

java - 使用构建器时无法执行自定义反序列化

java - Double 数据类型的意外行为

javascript 和弄乱字符串的原型(prototype)

c++ - std::map 覆盖错误的键

javascript - JavaScript 'get middle letter' 代码 war 挑战的三元运算符函数