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.

Solution

public class Solution {

    public Map<String, Boolean> map = new HashMap<String, Boolean>();

    public boolean canWin(String s) {
        if(map.containsKey(s)) return map.get(s);
        char[] array = s.toCharArray();
        for(int i = 0; i < array.length - 1; i++) {
            if(array[i] == '+' && array[i+1] == '+') {
                array[i] = '-';
                array[i+1] = '-';
                if(!canWin(new String(array))) {
                    map.put(s, true);
                    return true;
                }
                array[i] = '+';
                array[i+1] = '+';
            }
        }
        map.put(s, false);
        return false;
    }


}

results matching ""

    No results matching ""