字节跳动8.11后端开发笔试第二题

有原题,不过是求密码,不是求原码。用的是python,思路和大家也是一样的,一共写了三个版本,卡的要求都很细节,不过都是值得注意的地方
#第一版,过66.7
while True:
    try:
        N,K = map(int,input().split())
        arr = input()
        arr = list(map(int,' '.join(arr).split()))
        orr = [arr[0]]
        i = 1
        L = 1
        while L<N:
            temp = 0
            if i<=K-1:
                temp+=sum(orr[:i])
            else:
                temp+=sum(orr[i-K+1:i])
            temp+=arr[i]
            orr.append(temp%2)
            L+=1
            i+=1
        re = orr
        print(''.join(str(i) for i in re))
    except:
        break
第一版,提示超时,每次计算temp都是取得orr的K个元素求和,时间复杂度是K*N,所以进行优化,temp进行减头加尾,时间复杂度变为N,写了第二版
#第二版,过83
while True:
    try:
        N,K = map(int,input().split())
        arr = input()
        arr = list(map(int,' '.join(arr).split()))
        orr = [arr[0]]
        i = 1
        #print(orr)
        flag = 0
        while len(orr)<N:
            #print(arr[i],orr)
            temp = 0
            if i<=K-1:
                temp+=sum(orr[:i])
                flag = temp
            else:
                temp = flag
                #temp+=sum(orr[i-K+1:i])
                temp+=orr[i-1]-orr[i-K]
                flag = temp
            temp+=arr[i]
            orr.append(temp%2)
            #print('抑或之后',orr)
            i+=1
        re = orr
        print(''.join(str(i) for i in re ))
    except:# Exception as a:
        #print(a)
        break
第二版,提示超出内存,这是做题过程中第二次碰到,第一次是在shopee,那一次没找出问题所在,这一次,想到,输入字符串变成数组可能会导致内存超出,尝试改了一下,不改变字符串,继续提交第三版
#第三版 ac
while True:
    try:
        N,K = map(int,input().split())
        arr = input()
        #arr = list(map(int,' '.join(arr).split()))
        orr = arr[0]
        i = 1
        flag = 0
        while len(orr)<N:
            temp = flag
            if i<K:
                temp+=int(orr[i-1])
                flag = temp
            else:
                temp+=int(orr[i-1])-int(orr[i-K])
                flag = temp
            temp+=int(arr[i])
            orr+=str(temp%2)
            #print(orr)
            i+=1
        #re = orr
        #print(''.join(str(i) for i in re ))
        print(orr)
    except:# Exception as a:
        #print(a)
        break
第三版终于ac了,小细节还挺多,平时计算求和直接取数组某一段,还有习惯于对数组进行操作,所以需要类型转换导致内存超出。习惯还需养好。








#字节跳动##笔试题目#
全部评论
能否让字符串想加,再直接按照给的N,K,提前子字符串
点赞 回复 分享
发布于 2019-08-12 11:03
/* 7 4 1110100110 */ #include <iostream> #include <string> using namespace std; string fun(int N, int K, string str); int main() { int N, K; string str; cin >> N >> K; cin >> str; string res = fun(N, K, str); cout << res; } string fun(int N, int K, string str) { string res(N + K - 1, '0'); for (int i = 0; i < N; ++i) { char ch = str[i] - '0'; for (int j = 1; j < K; ++j) { ch = ch ^ (res[K - 1 + i - j] - '0') + '0'; } res[K - 1 + i] = ch; } res = res.substr(K - 1, N + K - 1); return res; }
点赞 回复 分享
发布于 2019-08-12 10:56

相关推荐

烤点老白薯:这种东西到时候公众号搜索都有的
点赞 评论 收藏
分享
评论
1
2
分享

创作者周榜

更多
牛客网
牛客企业服务