Program opened below. You can scroll through the algorithm, Java code and output.
Program 06
Remove Consecutive Repeated Characters
Question
Read a word and replace every run of repeated consecutive characters with a single occurrence.
Algorithm
Step 1: Start and create a Scanner.
Step 2: Accept the input word.
Step 3: Initialize an empty result string.
Step 4: Set the character position to zero.
Step 5: Run a loop until the last character has been examined.
Step 6: Read the character at the current position.
Step 7: If it is the first character, add it to the result.
Step 8: Otherwise compare it with the immediately preceding character.
Step 9: If the two characters are different, add the current character to the result.
Step 10: If the characters are the same, do not add anything.
Step 11: Advance to the next character.
Step 12: Repeat the comparison for the entire word.
Step 13: Display the result containing one character per consecutive run.
Step 14: Stop.
Java program
Javaimport java.util.*;
class RemoveRuns {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word = sc.next();
String result = "";
for (int i = 0; i < word.length(); i++) {
if (i == 0 || word.charAt(i) != word.charAt(i - 1)) {
result += word.charAt(i);
}
}
System.out.println(result);
}
}Sample output
Input: Piiiiiccckk
Output: Pick