B.怕npy的牛牛

牛牛算数

https://ac.nowcoder.com/acm/contest/9556/A

B.怕npy的牛牛-JAVA版

public int Maximumlength (String x) {
        int n=0,p=0,y=0;
        int index=0;
        int max=0;
        for (int i=0;i<x.length();i++) {
            if (x.charAt(i)=='n') n++;
            if (x.charAt(i)=='p') p++;
            if (x.charAt(i)=='y') y++;
            while(n>=1 && p>=1 && y>=1) {//如果三个字符出现次数都>=1 则说明前面已经同时出现npy了
                if (x.charAt(index) == 'n')n--;
                if (x.charAt(index) == 'p') p--;
                if (x.charAt(index) == 'y') y--;//这个操作相当于找到前面字符串中,npy三个字符每个字符最后出现的位置的最小值 则不会同时出现npy三个字符的字符串是 x(index ,i]
                index++;
            }
            max = Math.max(max,i-index+1);
        }
        return max;
    }

B.怕npy的牛牛-python版
B题我用的是滑动窗口的思想,就是维护一个数组res,不让他同时出现npy三个字母即可,
特别注意的是,如果当前字符是npy之一,当该字符放进去时,res就同时包含了npy,则此时更新res,找到npy三个字符最后一个出现位置的最小值即 index=min(last_index_n,last_index_p,last_index_y) 将index之前的remove尾部加上该字符即可,代码如下:

def Maximumlength(self , x ):
        res =[]
        maxx=0
        for s in x:
            if s not in ['p','n','y'] :
                res.append(s)
            elif s=='n' and ('p' not in res or 'y' not in res):
                res.append(s)
            elif s=='p' and ('n' not in res or 'y' not in res):
                res.append(s)
            elif s=='y' and ('p' not in res or 'n' not in res):
                res.append(s)
            else :
                le = len(res)-1
                if s=='n':
                    index = min(le-res[::-1].index('p'),le-res[::-1].index('y'))
                if s=='p':
                    index = min(le-res[::-1].index('n'),le-res[::-1].index('y'))
                if s=='y':
                    index = min(le-res[::-1].index('p'),le-res[::-1].index('n'))
                maxx = max(maxx,len(res))
                res = res[index+1:]+[s]
        return max(maxx,len(res))
全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务