Last active
October 21, 2017 01:52
-
-
Save TT--/e5449316074cd4e7d3a98b44a7c5f95e to your computer and use it in GitHub Desktop.
input a string of lowercase. recursively remove instances of doubled characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* TT 2017-10-20 | |
* | |
* solution for "Super Reduced String" | |
* https://www.hackerrank.com/challenges/reduced-string | |
* | |
* similar "brute force" ways: | |
* | |
* with stringbuilder | |
* https://github.com/ebolat/HackerRank/blob/master/Algorithms/Strings/Super%20Reduced%20String/Solution.java | |
* | |
* with string | |
* https://codereview.stackexchange.com/questions/150921/super-reduced-string | |
* | |
* Better: | |
* ======= | |
* "diy" stack of char | |
* (ans to question above) | |
* https://codereview.stackexchange.com/a/150946 | |
* | |
* actual stack of Character: | |
* https://github.com/rshaghoulian/HackerRank_solutions/blob/master/Algorithms/Strings/Super%20Reduced%20String/Solution.java | |
* | |
* | |
*/ | |
import java.util.Scanner; | |
public class ReduceString { | |
static String super_reduced_string(String s) { | |
// Complete this function | |
String reduced = s; | |
for (int i = 0; i < s.length() - 1; i++) { // up to 2nd-last char | |
// System.out.printf("i= %d length= %d s= %s%n", i, s.length(), s); | |
if (s.charAt(i) == s.charAt(i + 1)) { | |
// remove i,i+1 | |
// System.out.printf("remove from pos %d: %c%c%n", i, s.charAt(i), s.charAt(i + 1)); | |
reduced = s.replace(s.substring(i, i + 2), ""); | |
// System.out.println("reduced is " + reduced); | |
reduced = super_reduced_string(reduced); | |
// not written on one line, to examine the effect of having no | |
// return statement here - | |
// recursive calls stack, when starting to unwind, execution returns to this point, | |
// skipping the start of the for loop, so that i ends up exceeding string length | |
// and the reduced string grows back to an earlier state (! wrong - although it can | |
// produce valid strings as well) | |
return reduced; | |
// return super_reduced_string(reduced); | |
} | |
} | |
reduced = reduced.equals("") ? "Empty String" : reduced; | |
return reduced; | |
} | |
public static void main(String[] args) { | |
// Scanner in = new Scanner(System.in); | |
// String s = in.next(); | |
String s = "aaabccddd"; | |
// String s = "abcdefgh"; | |
// String s = "aabbcc"; | |
String result = super_reduced_string(s); | |
System.out.println(result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment