240
生活,简单就好!

Python编程题17--字符串在另一个字符串中的位置

题目

给定字符串A和字符串B,请检测字符串A是否在字符串B中,如果存在则返回字符串B中每次出现字符串A的起始位置,否则返回 -1 。

例如:

给定一个字符串:GBRRGBRGG,另一个字符串:RG
那么字符串 RG 在 GBRRGBRGG 中出现的位置为 3,6

实现思路1

  • 设置一个列表,用于存储结果,分别计算出长字符串s1和短字符串s2的长度:len1、len2
  • 对长字符串s1进行遍历,遍历过程当索引下标到 len1 - len2 时,结束遍历
  • 遍历过程,对长字符串s1进行切片操作,起始索引为 i ,结束索引为 i + len2
  • 如果切片得到的结果恰等于 s2 ,那就说明 s2 在 s1 出现了,此时把本次出现的起始位置 i 添加到结果列表中
  • 最后,判断结果列表是否为空,不为空则返回结果,否则返回 -1

代码实现

def index_of_str(s1, s2):
    res = []
    len1 = len(s1)
    len2 = len(s2)
    if s1 == "" or s2 == "":
        return -1
    for i in range(len1 - len2 + 1):
        if s1[i] == s2[0] and s1[i:i+len2] == s2:
            res.append(i)
    return res if res else -1

str1 = "cdembccdefacddelhpzmrtcdeqpjcde"
str2 = "cde"
print("字符串 {} 在另一个字符串 {} 中出现的位置:{} ".format(str2, str1, index_of_str(str1, str2)))

实现思路2

  • 设置一个列表,用于存储结果
  • 设置一个变量index,用于表示短字符串s2在长字符串s1中出现的位置,默认为 0
  • 通过短字符串s2,对长字符串s1进行分割操作,得到的结果存储到 split_list
  • 对split_list进行遍历,遍历完倒数第二个元素时,结束遍历
  • 遍历过程,把 index 添加到结果列表中
  • 最后,判断结果列表是否为空,不为空则返回结果,否则返回 -1

注意:split() 分割操作时,如果所指定分割串不在字符串中,那么会返回字符串本身。

代码实现

def index_of_str(s1, s2):
    res = []
    index = 0
    if s1 == "" or s2 == "":
        return -1
    split_list = s1.split(s2)
    for i in range(len(split_list) - 1):
        index += len(split_list[i])
        res.append(index)
        index += len(s2)
    return res if res else -1

str1 = "cdembccdefacddelhpzmrtcdeqpjcde"
str2 = "cde"
print("字符串 {} 在另一个字符串 {} 中出现的位置:{} ".format(str2, str1, index_of_str(str1, str2)))

更多Python编程题,等你来挑战:Python编程题汇总(持续更新中……)

posted @ 2020-11-14 12:09  wintest  阅读(2537)  评论(0编辑  收藏  举报