首页 > 试题广场 >

01游戏

[编程题]01游戏
  • 热度指数:1138 时间限制:C/C++ 3秒,其他语言6秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
对01字符串进行一些操作,01字符串上的0和0相邻时会变成1,而1和1相邻时会在字符串上消失,而0和1相邻时什么都不会发生,问这个字符串最后会变成什么样。

示例1

输入

"00110001"

输出

"01"

说明

00110001→1110001→10001→1101→01  

备注:
,字符串上的合并消失应优先与左边进行,例如000,中间的0优先与左边的0合并变为10,消失同理

/**
 * 
 * @param str string字符串 初始字符串
 * @return string字符串
 */
function solve( str ) {
    // write code here
    let s=[];
    s.push(str[0]);
    let a=str[0];
    for(let i=1;i<str.length;i++){
        if(s.length==0){
            s.push(str[i]);
            a=str[i];
        }else if(a==1&&str[i]==1){
            s.pop();
            while(s[s.length-1]==1&&s[s.length-2]==1){
                s.pop();
                s.pop();
            }
            if(s.length!=0) a=s[s.length-1];
            
        }else if(a==0&&str[i]==0){
            s.pop();
            s.push(1);
            while(s[s.length-1]==1&&s[s.length-2]==1){
                s.pop();
                s.pop();
            }
            if(s.length!=0) a=s[s.length-1];
            
        }else{
            s.push(str[i]);
            a=str[i];
        }
    }
    return s.toString().split(/,/g).join("");
}
一个栈,两个指针,要注意在11和00后对之前的项进行再次11的循环处理。
编辑于 2020-09-04 16:05:06 回复(3)

问题信息

难度:
1条回答 2290浏览

热门推荐

通过挑战的用户

查看代码