stumped on a Java interview, need some hints

后端 未结 8 2125
天涯浪人
天涯浪人 2021-01-30 18:00

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

8条回答
  •  滥情空心
    2021-01-30 18:51

    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

    • left to right or right-to-left (my version uses left-to-right)
    • depth-first (or breadth-first) (my version uses depth-first)

提交回复
热议问题