yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #294. Flip Game II #250

Open yokostan opened 5 years ago

yokostan commented 5 years ago
class Solution {
    public boolean canWin(String s) {
        if (s == null || s.length() < 2) return false;
        for (int i = 0; i < s.length() - 1; i++) {
            if (s.charAt(i) == '-') continue;
            if (s.charAt(i) == '+' && s.charAt(i + 1) == '+') {
                String s2 = s.substring(0, i) + "--" + s.substring(i + 2);
                if (!canWin(s2)) return true;
            }
        }
        return false;
    }
}

If we use HashMap based on the above solution, we can get 10 times faster by memorizing the permutations we already judged.

class Solution {
    public boolean canWin(String s) {
        if (s == null || s.length() < 2) return false;
        Map<String, Boolean> map = new HashMap<String, Boolean>();
        return helper(s, map);
    }

    public boolean helper(String s, Map<String, Boolean> map) {
        if (map.containsKey(s)) {
            return map.get(s);
        }
        for (int i = 0; i < s.length() - 1; i++) {
            if (s.charAt(i) == '-') continue;
            if (s.charAt(i) == '+' && s.charAt(i + 1) == '+') {
                String s2 = s.substring(0, i) + "--" + s.substring(i + 2);
                if (!helper(s2, map)) {
                    map.put(s, true);
                    return true;
                }
            }
        }
        map.put(s, false);
        return false;
    }
}
yokostan commented 5 years ago

Also, we can use s.startsWith("++", i) to replace the condition statement.

yokostan commented 5 years ago

The HashMap eliminates duplicate steps in between.