Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

[JAVA] Create a code using String removeDuplicates(String s) that creates and re

ID: 3792993 • Letter: #

Question

[JAVA] Create a code using String removeDuplicates(String s) that creates and returns a new string with all the consecutive occurrences of the same character turned into a single character. For example, when called with the string “aabbbbbabbbbccccddd”, this method would create and return the string “ababcd”. (Hint: loop through the characters of the string, and add the character to the result only if it is different from the previous character. Be careful at the beginning of the string.)

so if the the input is aaabbbcccddee, it will return abcde

Explanation / Answer

import java.util.Scanner;

public class Solution {
  
   public static void main(String[] args) {
       Scanner scanner=new Scanner(System.in);
       String s=scanner.next();
       String result="";
       char prev = 0;
       for(int i=0;i<s.length();i++){
           char ch=s.charAt(i);
           if(ch==prev){
               prev=ch;
           }else{
               result+=ch;
               prev=ch;
           }
       }
       System.out.println(result);
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote