首页 > 试题广场 >

牛牛与字符串1

[编程题]牛牛与字符串1
  • 热度指数:549 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
牛牛想知道在一个字符串s中是否有两个不重叠的子串"NB"和"BN"
例如,在一个字符串中出现一个子串为"NBN",那么就是有重叠的。
由于字符串可能会很长,所以牛牛无法解决该问题,所以他想请你帮忙,给定一个字符串s,如果两个不重叠的子串"NB"和"BN",返回"YES",反之,返回"NO"。
示例1

输入

"NBN"

输出

"NO"
示例2

输入

"NBYBN"

输出

"YES"

备注:
保证字符串只由大写字母组成
题解:https://blog.nowcoder.net/n/833d1cef0abc4de696b6e82f2c3982d6
RAHBTGCZPDNBN
第7个用例那个超长的有NBN,还输出YES?NBN不算重叠吗?
发表于 2021-05-11 10:52:41 回复(0)
"NBNNB"
这个测试用例应该输出YES吧?
发表于 2021-04-06 17:00:45 回复(0)
利用计数器统计出NB和BN的数量,都大于1就是YES
发表于 2021-10-20 17:40:40 回复(0)
垃圾题垃圾用例,全都有问题
发表于 2021-10-16 15:31:53 回复(0)
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
# 给定一个字符串s,如果有两个不重叠的子串"NB"和"BN",返回"YES",反之,返回"NO"。
# @param s string字符串 代表题意中的字符串s
# @return string字符串
#
class Solution:
    def solve(self , s ):
        # write code here
        for i in range(len(s)):
            if s[i:i+2]=="NB":
                s = s[:i]+s[i+2:]
                for j in range(len(s)):
                    if s[j:j+2]=="BN":
                        return "YES"
                        break
                return "NO"
                break
        return "NO"
          
             
                    
发表于 2021-04-22 21:26:00 回复(0)
class Solution:
    def solve(self , s ):
        # write code here
        bn=0
        nb=0
        res = list(s)
        for i in range(0,len(res)-1):
            if res[i]=='N' and res[i+1]=='B':
                res.pop(i)
                res.pop(i)
                break
        for i in range(0,len(res)-1):        
                if res[i]=='B' and res[i+1]=='N':
                    return "YES"
        return "NO"
发表于 2021-03-26 15:01:16 回复(0)
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 给定一个字符串s,如果有两个不重叠的子串"NB"和"BN",返回"YES",反之,返回"NO"。
     * @param s string字符串 代表题意中的字符串s
     * @return string字符串
     */
    string solve(string s) {
        // write code here
        int count0 = 0, count1 = 0;
        for(int i = 0; i < s.size(); i++){
            if(count0 >= 1 && count1 >= 1){
                return "YES";
            }
            if(s[i] == 'N' && s[i + 1] == 'B' && count0 == 0){
                count0 ++;
                i ++;
            } else if(s[i] == 'B' && s[i + 1] == 'N'){
                count1 ++;
                i ++;
            }
        }
        if(count0 >= 1 && count1 >= 1){
            return "YES";
        }
        return "NO";
    }
};

发表于 2021-03-07 13:57:36 回复(0)