yokostan / Leetcode-Solutions

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

Leetcode #293. Flip Game #249

Open yokostan opened 5 years ago

yokostan commented 5 years ago

My Brute force super slow:

class Solution {
    public List<String> generatePossibleNextMoves(String s) {
        List<String> res = new ArrayList<String>();
        if (s == null || s.length() == 0) return res;

        for (int i = 0; i < s.length() - 1; i++) {
            if (s.charAt(i) == '+' && s.charAt(i + 1) == '+') {
                String out = s.substring(0, i) + '-' + '-' + s.substring(i + 2);
                res.add(out);
            }
        }

        return res;
    }
}

Well, after adding one line it beats 100%.

class Solution {
    public List<String> generatePossibleNextMoves(String s) {
        List<String> res = new ArrayList<String>();
        if (s == null || s.length() == 0) return res;

        for (int i = 0; i < s.length() - 1; i++) {
            if (s.charAt(i) == '-') continue;
            if (s.charAt(i) == '+' && s.charAt(i + 1) == '+') {
                String out = s.substring(0, i) + '-' + '-' + s.substring(i + 2);
                res.add(out);
            }
        }

        return res;
    }
}