1. 交錯字串
    1. 題目
    2. 解題

交錯字串

交錯字串

apcs歷屆

題目

嗨,今天又要來寫APCS的歷屆了,來看一下題目吧~
pic
簡單來說就是要讓他偵測一個字串當中最長的為k的交錯字串。

解題

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# append到一個list 用for 去對數字 然後如果開始!= k 就print(i) break
# 1 -> 1 2 4 -> 2
# 3 -> 23222 -> 3
# 2 -> 3225 -> 8
def count(string):
list1 = [] #紀錄幾個
countbig = 0
countsmall = 0
for i in range(len(string)):
#print(countbig, countsmall)
if string[i].isupper():
if countbig == 0 and countsmall != 0:
list1.append(countsmall)
countsmall = 0
countbig += 1
else:
countbig += 1
else:
if countsmall == 0 and countbig != 0:
list1.append(countbig)
countbig = 0
countsmall += 1
else:
countsmall += 1
if countbig != 0:
list1.append(countbig)
elif countsmall != 0:
list1.append(countsmall)
return list1

#[1, 2, 4]
k = int(input())
string = input()
list1 = count(string)
#print(list1)
now = 0
long = 0
for i in list1:
if i == k:
now += k
if now > long:
long = now
elif i > k:
#now += k
if now + k > long :
long = now + k
now = k
elif i < k:
now = 0
print(long)

簡單來說這個程式就是將大小寫的每一個長度處存出來存到list,假設”aBBccc”就是[1, 2, 3],接下來回傳出來,我們再去判斷如果K跟他一樣長我們就把現有的加上K,阿如果比較大就先看加上K之後會不會比較長,不過要注意的就是可能他不能延續,所以要重新把now = k,再來如果比較小就直接now歸零。