Flip Game ll

You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, you and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other person will be the winner.

Write a function to determine if the starting player can guarantee a win.

For example, given s = "++++", return true. The starting player can guarantee a win by flipping the middle "++" to become "+--+".

Follow up:
Derive your algorithm's runtime complexity.

    public boolean canWin(String s) {
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i + 1< s.length(); i ++) {
            if (s.charAt(i) == s.charAt(i + 1) && s.charAt(i) == '+') {
                set.add(i);
            }
        }

        return helper(set);
    }

    public boolean helper(Set<Integer> set) {
        for (int move : set) {

            Set<Integer> newSet = new HashSet<>(set);
            newSet.remove(move);
            boolean hasLeft = newSet.remove(move - 1);
            boolean hasRight = newSet.remove(move + 1);
            if (!helper(newSet)) {
                return true;
            }

            newSet.add(move);
            if (hasLeft) newSet.add(move - 1);
            if (hasRight) newSet.add(move + 1);
        }
        return false;
    }

results matching ""

    No results matching ""