293/294 Flip Game I and II -- back tracking ing

293. 一个input 只有 + 或者-, 每次只能把 “连续2个”+ 变成- 号,下一轮换另一个人做同样操作,如果不存在连续的+,则这个人就失败了。
Input: s = "++++" Output: [ "--++", "+--+", "++--" ]
给你一个初始化的字符串,问你下一次可能的结果。

算法: 简单的字符串处理,只要找到连续两个+ 就变成- 然后存入结果中。code如下:需要注意的就是 首和尾是否存在字符串了。 用i-1>0 以及 i+1 < length 来判断首尾。
    public List<String> generatePossibleNextMoves(String s) {
        List<String> result = new ArrayList<>();
        if(s.length()<2) return result;
        
        for(int i=1; i<s.length(); i++){
            if(s.charAt(i) == '+' && s.charAt(i-1) == '+'){
              String str = (i-1 > 0? s.substring(0,i-1): "") + "--"+ ( i+1< s.length() ? s.substring(i+1,s.length()): "");
              result.add(str);  
            }
        }
        
        return result;
    }

294. 在293基础上问你 starting player 是否一定能赢

分析: 两个player 成为 play0 和 play1,  存在一条路径,让 play0 做出某个选择, play1 无论如何选择 最终都能导致 play1 fail 掉。

猜你喜欢

转载自www.cnblogs.com/keepAC/p/9967195.html