写一个函数找子串在主串中的所有位置,串要用链表结构。
时间: 2023-06-25 10:07:02 浏览: 92
可以参考以下的链表结构:
```python
class Node:
def __init__(self, val):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, val):
if not self.head:
self.head = Node(val)
else:
curr = self.head
while curr.next:
curr = curr.next
curr.next = Node(val)
```
接下来,我们可以编写一个函数来查找子串在主串中的所有位置:
```python
def find_substring_positions(main_str, sub_str):
if not main_str or not sub_str:
return []
main_len = len(main_str)
sub_len = len(sub_str)
positions = []
for i in range(main_len - sub_len + 1):
j = 0
curr = main_str[i]
while j < sub_len and curr == sub_str[j]:
j += 1
if j == sub_len:
positions.append(i)
break
if i+j == main_len:
break
curr = main_str[i+j]
return positions
```
我们可以使用上述函数来查找主串 `hello world` 中所有子串 `lo` 的位置:
```python
main_str = LinkedList()
for c in "hello world":
main_str.append(c)
sub_str = LinkedList()
for c in "lo":
sub_str.append(c)
positions = find_substring_positions(main_str, sub_str)
print(positions) # 输出: [3, 8]
```
输出结果为 `[3, 8]`,表示子串 `lo` 在主串 `hello world` 中出现在位置 3 和 8。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)