293-翻转游戏

翻转游戏

题目

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 twoconsecutive "++" 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 compute all possible states of the string after one valid move.

For example, given s = "++++", after one move, it may become one of the following states:

[
  "--++",
  "+--+",
  "++--"
]

If there is no valid move, return an empty list [].

你正在和你的朋友玩儿下面的翻转游戏:给定一个仅包含+和-的字符串,你和你的朋友轮流可以将"++"变成"--".当一个人没办法再行动的时候游戏就结束了,另一个人就赢了.

写一个方法来计算在一个合法的移动后的所有的可能状态.

例如,给定s="++++",一个移动之后,下面是可能出现的状态

[
  "--++",
  "+--+",
  "++--"
]

如果没有合法的移动,返回一个空集合即可.

思路

刚开始会以为计算谁会赢,会涉及到动态规划,但是题目的意思是计算一个合法的移动后的所有的可能状态,因此我们只需要遍历s,判断即可

代码

public class Solution {  
    public List<String> generatePossibleNextMoves(String s) {  
        List<String> result = new ArrayList<String>();  
        for (int i = 0; i < s.length() - 1; i++) {  
            if (s.charAt(i) == '+' && s.charAt(i + 1) == '+') {  
                String flip = s.substring(0, i) + "--" + s.substring(i + 2);  
                result.add(flip);  
            }  
        }  
        return result;  
    }  
}  
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Chapter 1 In the year 1878, I took my degree of Doctor of...
    foxgti阅读 4,181评论 0 6
  • 最近发现跟老公的三观越来越相契合了,我们出自于价值观非常不同的两个家庭,近二十年携手走来,一路上磕磕绊绊,有过...
    静远心阅读 49评论 0 1
  • 昨天和同事,大学同学一起去了杭州听了唐唐忠汉老师的课程。 本来报名的时候还有点坎坷,差点没报上,后来双十二开放了通...
    设计师周文斌阅读 374评论 0 1
  • 想:2019年8月1日前收入6万。 找:业力小伙伴建君,每周二下午5点半见面1小时。 给:今天早上早起帮家人包水饺...
    境由心生_4dd3阅读 185评论 0 0
  • 今天大课间,操场上下起了彩纸雨,彩纸有的像蝴蝶翩翩起舞,有的像仙女们从天空中飞下来。过了一会儿,它们有的落在...
    沈昕月阅读 168评论 0 0

友情链接更多精彩内容