Java String Manipulation : Comparing adjacent Characters in Java

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

    Looks like you are solving codingbat problems, it is good,

    I m a beginner too. This exercise is supposed to be just using recursion

    This is my solution:

    public String stringClean(String str) {
      if (str.length() <= 1)
          return str;
    
      String adj1 = str.substring(0,1);
      String adj2 = str.substring(1,2);
    
      String rest = str.substring(1);
    
      if (adj1.equals(adj2)) {
          return stringClean(rest);
      } else
          return adj1 + stringClean(rest);
    }
    

    Hope it helps

提交回复
热议问题