Memorizing Solution with HashSet


  • 0
        public boolean canWin(String s) {
            if(s == null || s.length() <= 1)  return false;
            Set<String> set = new HashSet<>();
            return helper(s, set);
        }
            
        public boolean helper(String s, HashSet<String> set) {
            if(set.contains(s)) return true;
            for(int i = 0; i < s.length() - 1; ++i) {
                if(s.startsWith("++", i)) {
                    String t = s.substring(0, i) + "--" + s.substring(i+2);
                    if(!helper(t, set)) {
                        set.add(s);
                        return true;
                    }
                }
            }
            return false;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.