Online challenge on Hacker Rank.
Problem Statement
Steve has a string,
S, consisting ofnlowercase English alphabetic >letters. In one operation, he can delete any pair of adjacent letters with same >value. For example, string"aabcc"would become either"aab"or"bcc">after operation.Steve wants to reduce as much as possible. To do this, he will repeat the >above operation as many times as it can be performed. Help Steve out by finding >and printing
S's non-reducible form!Note: If the final string is empty, print
Empty String.Input Format
A single string,
S.Constraints
\$1 ≤ n ≤ 100\$
Output Format
If the final string is empty, print Empty String; otherwise, print the final >non-reducible string.
Sample Input
aaabccdddSample Output
abd
Solution Code
public class Solution {
private static String solve(String input) {
int len = input.length();
int i = 0;
while (i < len - 1) {
char current = input.charAt(i);
char next = input.charAt(i+1);
if (current == next) {
input = input.substring(0, i) + input.substring(i+2);
len = input.length();
i = 0;
continue;
}
i++;
}
if (input.length() == 0) {
return "Empty String";
}
return input;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println(solve(s.next()));
}
}
This is a brute-force solution, as I feel kind of confused when dealing with string algorithms. Hope for some good suggestions here.
LinkedListof characters instead of keepingStrings. You should be able to prevent all thesubstring()calls. \$\endgroup\$