給定乙個字串s和乙個整數k,如果s中正好有連續的k個』0』字元出現,把k個』0』字元去掉,返回處理後的字串。
如s=『a00b』,k=2,返回』ab』
s=『a0000b000』,k=3,返回』a0000b』
維護乙個計數count,表示找到幾個連續的』0』,維護找到的第乙個』0』的位置start,遍歷字串,過程中,
def
remove_k_zeros1
(s, k)
:def
remove
(chars, start, count)
:while count:
chars[start]
=none
start +=
1 count -=
1if s is
none
or k <1:
return s
chars =
list
(s) start, count =-1
,0for i in
range
(len
(chars)):
if chars[i]
=='0'
: count +=
1 start = i if start ==-1
else start
else
:if count == k:
remove(chars, start, count)
start, count =-1
,0if count == k:
remove(chars, start, count)
return
''.join(
[c for c in chars if c]
)
遍歷字串,直到最後,過程中
def
remove_k_zeros2
(s, k)
:def
remove
(chars, start, count)
:while count:
chars[start]
=none
start +=
1 count -=
1if s is
none
or k <1:
return s
chars =
list
(s) first =
0while
true
:while first <
len(chars)
and chars[first]
!='0'
: first +=
1if first ==
len(chars)
:break
last = first
while last <
len(chars)
and chars[last]
=='0'
: last +=
1if last - first == k:
remove(chars, first, k)
first = last
return
''.join(
[c for c in chars if c]
)
def
test_remove_k_zeros()
:assert
(remove_k_zeros1('',
2)==''
)assert
(remove_k_zeros2('',
2)==''
)assert
(remove_k_zeros1(
'a',2)
=='a'
)assert
(remove_k_zeros2(
'a',2)
=='a'
)assert
(remove_k_zeros1(
'a0',2
)=='a0'
)assert
(remove_k_zeros2(
'a0',2
)=='a0'
)assert
(remove_k_zeros1(
'a00b',2
)=='ab'
)assert
(remove_k_zeros2(
'a00b',2
)=='ab'
)assert
(remove_k_zeros1(
'a0000b000',3
)=='a0000b'
)assert
(remove_k_zeros2(
'a0000b000',3
)=='a0000b'
)assert
(remove_k_zeros1(
'a0000b000',4
)=='ab000'
)assert
(remove_k_zeros2(
'a0000b000',4
)=='ab000'
)if __name__ ==
'__main__'
: test_remove_k_zeros(
)
去掉字串中連續出現k個0的子串
去掉字串中連續出現k個0的子串 題目 給定乙個字串str和乙個整數k,如果str中正好有連續的k個 0 字元出現時,把k個連續的 0 去掉,返回處理後的字串。舉例 str a00b k 2,返回 a b str a0000b000 k 3,返回 a0000b 解答 使用變數count統計連續出現的0...
去掉字串中連續出現k個0的子串
題目 給定乙個字串str和乙個整數k,如果str中正好有連續的k個 0 字元出現時,把k個連續的 0 字元去除,返回處理後的字串。舉例 str a00b k 2,返回 a002 str a0000b000 k 3,返回 a0000b 難度 思路 對於處理字串各種問題,以前我都是以雙重巢狀著稱,時間複...
去掉字串中連續出現k個0的子串
題目 給定乙個字串s和乙個整數k,如果str中正好有連續的k個 0 字元出現時,把k個連續的 0 字元去除,返回處理後的字串。舉例 s a00b k 2,返回 ab s a0000b000 k 3,返回 a0000b 考慮邏輯分析能力和邊界處理問題。建立字串s對應的字元陣列arr count統計連續...