Java String Manipulation : Comparing adjacent Characters in Java

前端 未结 12 773
陌清茗
陌清茗 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条回答
  •  梦毁少年i
    2021-01-07 11:26

    For your code and the specific issue you have mentioned if the adjacent position is beyond the bounds of your string set adjacentChar to the null char as otherwise adjacentChar is seen as the last character in the string, which means that an append is not done.

    if(adjacentPosition != str.length()){
         adjacentChar = str.charAt(adjacentPosition);
         System.out.println("adjacentChar ::" + adjacentChar);
    }
    
    else {
         adjacentChar = '/u0000';
    }
    

    EDIT

    I think that the second issue you have mentioned is in this piece of code

     if(sb.toString().indexOf(startChar) != -1){
          sb.append(adjacentChar);
          System.out.println("Appended String in if part-->"
             + sb.toString());
     }
    

    As e and o are in the buffer from Hello they are being appended when Bookkeeper is being checked. I don't think you need that line so remove it and that should fix Hello Bookkeeper.

    Although Mohoamed's answer will also work.

提交回复
热议问题