Java String Manipulation : Comparing adjacent Characters in Java

前端 未结 12 644
陌清茗
陌清茗 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:25

    If you aren't restricted to use collections from java.util I recommend to use Set. See example below.

    public static String stringClean(String input) {
        Set result = new LinkedHashSet();
    
        for (char c : input.toCharArray()) {
            result.add(c);
        }
    
        StringBuilder sb  = new StringBuilder();
        for (char c : result)
            sb.append(c);
        return sb.toString();
    }
    

提交回复
热议问题