Java String Manipulation : Comparing adjacent Characters in Java

前端 未结 12 805
陌清茗
陌清茗 2021-01-07 10:57

i have the following problem
Given a string, return a \"cleaned\" string where adjacent chars that are the same have been reduced to a single char. So \"yyzzza\"

12条回答
  •  佛祖请我去吃肉
    2021-01-07 11:29

    public static String stringClean(String str) {
        if (str == null || "".equals(str)) {
            return str;
        }
        char lastChar = str.charAt(0);
        StringBuilder resultBuilder = new StringBuilder();
        resultBuilder.append(lastChar);
        for (int index = 1; index < str.length(); index++) {
            char next = str.charAt(index);
            if (lastChar != next) {
                resultBuilder.append(next);
                lastChar = next;
            }
        }
    
        return resultBuilder.toString();
    }
    

提交回复
热议问题