Java String Manipulation : Comparing adjacent Characters in Java

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

    How about:

    public String stringClean(String str) {
      if (str.length() < 2)return str; 
    
      String nextStr = str.substring(1);
    
      if (str.charAt(0) == str.charAt(1)) {
        return stringClean(nextStr);
      }
    
      else return str.substring(0,1) +  stringClean(nextStr);
    }
    

提交回复
热议问题