LeetCode 345. Reverse Vowels of a String (Easy)

反转字符串中的所有元音字母。

原始问题

https://leetcode.com/problems/reverse-vowels-of-a-string/

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:
Given s = “hello”, return “holle”.

Example 2:
Given s = “leetcode”, return “leotcede”.

Note:
The vowels does not include the letter “y”.

解题思路

双指针,一个left从头部开始找,另一个right从尾部开始找,若leftright均为元音,交换二者。截止条件为left >= right

AC代码

C语言

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#define checkVowel(c) (c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='A'||c=='E'||c=='I'||c=='O'||c=='U')

char * reverseVowels(char* s) {
char * left, *right;
char tmpc;

// Initialize pointer
left = s;
right = s;

while (*right != '\0') {
right++;
}

while (1) {
while (!checkVowel(*left)) {
left++;
}

while (!checkVowel(*right)) {
right--;
}

if (left < right) {
tmpc = *left;
*left = *right;
*right = tmpc;
left++;
right--;
} else {
return s;
}
}

return s;
}

这里判断是否为元音字母使用了宏定义,以此提高运行效率。

相关题目

LeetCode 344. Reverse String (Easy)

文章目录
  1. 1. 原始问题
  2. 2. 解题思路
  3. 3. AC代码
    1. 3.1. C语言
  4. 4. 相关题目
|