反转字符串中的元音字母
时间: 2024-03-06 20:47:45 浏览: 23
好的,这个问题很简单。可以使用双指针方法,分别从字符串的首尾开始遍历,找到第一对需要交换的元音字母,然后交换它们的位置。直到左指针大于右指针为止。以下是示例代码:
```python
def reverse_vowels(s: str) -> str:
vowels = set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'])
left, right = 0, len(s) - 1
s = list(s)
while left < right:
while left < right and s[left] not in vowels:
left += 1
while left < right and s[right] not in vowels:
right -= 1
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
return ''.join(s)
```
这个函数的输入是一个字符串,输出是反转元音字母后的字符串。时间复杂度为O(n),其中n是字符串的长度。
相关问题
统计字符串中元音字母python
可以使用 Python 中的 count() 方法和字符串切片来统计字符串中元音字母的个数。
以下是一个示例代码:
```python
s = "Python is a high-level programming language."
vowels = "aeiouAEIOU"
count = 0
for vowel in vowels:
count += s.count(vowel)
print("The number of vowels in the string is:", count)
```
输出结果为:
```
The number of vowels in the string is: 14
```
在这个示例中,我们定义了一个字符串变量 `s`,它包含了需要统计元音字母的字符串。我们还定义了一个包含所有元音字母的字符串变量 `vowels`。然后,我们使用 for 循环和 count() 方法来计算字符串 `s` 中每个元音字母的出现次数,并将它们累加到变量 `count` 中。最后,我们输出变量 `count` 的值,即为字符串 `s` 中元音字母的总个数。
c语言统计字符串中元音字母
可以使用以下代码来统计字符串中元音字母的个数:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int i, len, count = 0;
printf("Enter a string: ");
fgets(str, 100, stdin);
len = strlen(str);
for (i = 0; i < len; i++) {
if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' ||
str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U') {
count++;
}
}
printf("Number of vowels in the string: %d", count);
return 0;
}
```
该代码首先从用户输入中获取一个字符串,然后使用 `strlen()` 函数计算字符串的长度。接下来,使用循环遍历字符串中的每个字符并检查它是否为元音字母。如果是,则将计数器 `count` 的值增加1。最后,输出计数器 `count` 的值,即字符串中元音字母的个数。