[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);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.