1、问题描述:从给定的字符串中删除指定的子字符串,例如将字符串“abcdefgh”中子串“cd”删除,并显示结果。
我的python实现:
#!-*-coding:utf-8-*-
import sys,os
def delete_substr_method1(in_str, in_substr):
start_loc = in_str.find(in_substr)
in_str, in_substr = list(in_str), list(in_substr)
[len_str, len_substr] = len(in_str), len(in_substr)
res_str = in_str[:start_loc]
for i in range(start_loc + len_substr, len_str):
res_str.append(in_str[i])
res = ''.join(res_str)
return res
def delete_substr_method2(in_str, in_substr):
start_loc = in_str.find(in_substr)
len_substr = len(in_substr)
res_str = in_str[:start_loc] + in_str[start_loc + len_substr:]
return res_str
if __name__ == "__main__":
in_str = input("please input string:")
in_substr = input("please input substring:")
result = delete_substr_method2(in_str, in_substr)
print(result)
print("ok")
2、字符串循环右移n位。如abcdefg右移2位后为fgabcde.
#!-*-coding:utf-8-*-
#pythonic method
def circle_move_method1(input_str, k):
l = len(input_str)
return input_str[l - k:] + input_str[:l - k]
#traditional method, space complexity O(1),time complexity O(n)
def circle_move_method2(input_str, k):
input_str = list(input_str)
#l = len(input_str)
#for i in range(k):
# ch = input_str[l - 1]
# for j in range(l-1,0,-1):
# input_str[j] = input_str[j - 1]
# input_str[0] = ch
#return "".join(input_str)
#another imply style about comment block
for i in range(k):
input_str.insert(0, input_str.pop())
return "".join(input_str)
if __name__ == "__main__":
input_str = input("please input:")
n = int(input("input the move value:"))
print(circle_move_method2(input_str, n))