This is an interview problem that I am stuck on:
Given a string consisting of a, b and c\'s, we can perform the following operation: Take any two adjacent
Edit For fun I did my own version that operates on a char[] in-place:
public class Main {
public static void main(String[] args) {
System.out.println(solve("abbccaacba"));
}
private static int solve(String testCase) {
if (!testCase.matches("^[abc]*$"))
throw new IllegalArgumentException("invalid input");
char[] chars = new char[testCase.length()];
testCase.getChars(0, testCase.length(), chars, 0);
int remaining = chars.length;
for (int i=0; (i1);)
{
int next = i+1;
while (next < chars.length && (' '==chars[next]))
++next;
if (next >= chars.length)
break;
if (chars[i]!=chars[next])
{
switch (chars[i])
{
case 'a': chars[next] = ('b'==chars[next])? 'c':'b'; break;
case 'b': chars[next] = ('a'==chars[next])? 'c':'a'; break;
case 'c': chars[next] = ('b'==chars[next])? 'a':'b'; break;
}
chars[i] = ' '; // mark as removed
remaining--;
while (i>0 && (' '!=chars[i-1]))
--i;
if (' '==chars[i])
i = next;
}
else
++i;
}
return remaining;
}
}
See it live on http://ideone.com/yhK9t, with debug output:
a
Still do note caveats I mentioned in my comments: EDIT Huh, somehow I borked a comment saying that the answers would vary depending on the order of substitutions