Merges two strings together, using alternating characters from each, except that runs of the same character are kept together. For example, (“abcde”, “xyz”) returns “axbyczde” (“abbcde”, “xxxyzzzz”) returns “axxxbbyczzzzde” Given the code below, the output I get is “axbxbcydzezzzz” Not only does this fail to preserve the runs, but it also adds and removes some characters. Some help as to what is wrong with my code would be much appreciated. Thank you in advance.
public class Test { public static void main(String[] args) { String t = "abbcde"; String s = "xxxyzzzz"; String result = ""; char tcurrent = t.charAt(0); char scurrent = s.charAt(0); result += tcurrent; result += scurrent; int i = 1; int j = 1; while (i < t.length() && j < s.length()) { if (tcurrent == t.charAt(i)) { result += t.charAt(i); i++; } if (scurrent == t.charAt(j)) { result += s.charAt(j); j++; } else { tcurrent = t.charAt(i); scurrent = s.charAt(j); result += t.charAt(i); result += s.charAt(i); i++; j++; } } while (i < t.length()) { result += t.charAt(i); i++; } while (j < s.length()) { result += s.charAt(i); j++; } System.out.println(result); } }
Advertisement
Answer
To start, there is a problem in the beginning when you do result += scurrent; without first checking t.charAt(1) and following.
Further, there is a copy paste error: if (scurrent == t.charAt(j)) –> should be s.charAt(j)
Finally, another copy-paste error at the end: result += s.charAt(i) –> should be charAt(j)
Conceptually, what you are doing wrong is alternating between s and t all the time. Instead, you should be checking only one string at a time and run a while loop until you encounter a different character:
public static void main(String[] args) { String t = "abbcde"; String s = "xxxyzzzz"; String result = ""; int tNextIndex = 0; int sNextIndex = 0; /* alternate while both strings have characters left */ while (tNextIndex < t.length() && sNextIndex < s.length()) { char tPreviousChar = t.charAt(tNextIndex++); result += tPreviousChar; while (tNextIndex < t.length() && t.charAt(tNextIndex) == tPreviousChar){ result += tPreviousChar; tNextIndex++; } char sPreviousChar = s.charAt(sNextIndex++); result += sPreviousChar; while (sNextIndex < s.length() && s.charAt(sNextIndex) == sPreviousChar){ result += sPreviousChar; sNextIndex++; } } /* if either of the string was finished, add the remainder of the other one to the result */ while (tNextIndex < t.length()) { result += t.charAt(tNextIndex++); } while (sNextIndex < s.length()) { result += s.charAt(sNextIndex++); } System.out.println(result); }