/** * Merges two strings together, using alternating characters from each, * exc
ID: 3726726 • Letter: #
Question
/**
* Merges two strings together, using alternating characters from each,
* except that runs of the same character are kept together. For example,
* <ul>
* <li><code>mergePreservingRuns("abcde", "xyz") returns "axbyczde"
* <li><code>mergePreservingRuns("abbbbcde", "xyzzz") returns "axbbbbyczzzde"
* </ul>
* Either or both of the strings may be empty. If the first string
* is nonempty, its first character will be first in the returned string.
* @param t
* first string
* @param s
* second string
* @return
* string obtained by merging characters from t and s, preserving runs
*/
public static String mergePreservingRuns(String t, String s)
{
// TODO
return null;
}
Explanation / Answer
int strTLen, strSLen;
strTLen = t.length(); // length of t
strSLen = s.length(); // length of s
String final = new String();
int tIn = 0; // index of t
int sIn = 0; // index of s
while (tIn < strTLen && sIn < strSLen) { // checking the strings till one of the strings is finished
char prevT = t.charAt(tIn++);
final += prevT;
while (tIn < strTLen && t.charAt(tIn) == prevT){ // if same character occurs looping again
final += prevT;
tIn ++;
}
}
char prevS = s.charAt(sIn++);
result += prevS;
while (sIn < strTLen && s.charAt(sIn) == prevS){
final += prevS;
sIn++;
}
}
//for the leftover string
while (tIn < strTLen) {
final += t.charAt(tIn ++);
}
while (sIn < strSLen) {
final += s.charAt(sIn++);
}
return(final);
// all the best
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.