python :已知一个字符串a,b。 字符串b中包含特殊符号’.’,’*’。 ‘.’表示该字符可以变成任意字符,’* ‘表示该字符的前一个字符可以变成任意多个。 现在我们想知道b可否通过特殊符号变成a。 a* 可以转化为a,aa,aaa,aaaa…
时间: 2023-02-11 19:57:14 浏览: 102
题目要求判断字符串b能否通过特殊符号变成字符串a。其中'.'表示该字符可以变成任意字符,'*'表示该字符的前一个字符可以变成任意多个。
可以使用递归的方法来判断。从两个字符串的最后一个字符开始递归,如果b的当前字符是'.'或者和a的当前字符相同,则继续递归下一个字符。如果b的当前字符是'*',则分别递归b的当前字符和前一个字符出现0次、1次、2次...直到字符串a被匹配完。
代码示例:
```
def isMatch(s, p):
if not p:
return not s
first_match = bool(s) and p[0] in {s[0], '.'}
if len(p) >= 2 and p[1] == '*':
return (isMatch(s, p[2:]) or
first_match and isMatch(s[1:], p))
else:
return first_match and isMatch(s[1:], p[1:])
```
相关问题
python已知一个字符串中存放了若干用空格分隔的单词,统计每个单词出现的次数。
可以使用Python中的字典来实现单词计数。具体步骤如下:
1. 将字符串按照空格分割成单词列表。
2. 遍历单词列表,对于每个单词,如果该单词已经在字典中,将该单词计数加1,否则将该单词添加到字典中,并将其计数初始化为1。
3. 最后遍历字典,输出每个单词及其对应的计数。
下面是使用Python实现的代码示例:
```python
string = "hello world hello python world"
word_list = string.split()
word_count = {}
for word in word_list:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
for word, count in word_count.items():
print(word, count)
```
输出结果:
```
hello 2
world 2
python 1
```
已知a.txt 文件中有这样的一个字符串:“fgihcex jkamdnoarzsvaybpltu”请编写程序读取数据内容,把数据排序后写入b.txt中。
好的,以下是一个Python的程序示例:
```python
with open('a.txt', 'r') as f:
data = f.read().strip() # 读取文件内容并去除首尾空格
sorted_data = sorted(data) # 对字符串进行排序
with open('b.txt', 'w') as f:
f.write(''.join(sorted_data)) # 将排序后的字符串写入文件中
```
这个程序会读取名为 `a.txt` 的文件,将其中的字符串排序后写入 `b.txt` 文件中。注意,这个程序假设文件中只有一个字符串,如果文件中包含多个字符串,需要根据具体情况进行修改。