0%

leetcode 344 Reverse String || leetcode 345 Reverse Vowels of a String

leetcode Reverse String

Write a function that takes a string as input and returns the string reversed.

Example: Given s = "hello", return "olleh". 题目地址:leetcode Reverse String

题意:给定一个字符串,让你逆序

思路:

双指针,直接置换

C++

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
string reverseString(string s) {
for(int L = 0,R = s.size()-1; L < R;L++,R--){
char temp = s[L];
s[L] = s[R];
s[R] = temp;
}
return s;
}
};

也可以直接用swap

1
2
3
4
5
6
7
8
9
class Solution {
public:
string reverseString(string s) {
for(int L = 0,R = s.size()-1; L < R;L++,R--){
swap(s[L],s[R]);
}
return s;
}
};

 

Python 直接oneline

1
2
3
4
5
6
7
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return s[::-1]

 


leetcode  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".

题目地址:leetcode Reverse Vowels of a String

题意:给定一个字符串,把它的所有元音字母逆序

思路:同样双指针,遇到元音(a,e,i,o,u 注意大小写)就停下来

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
bool isVowels(char x){
x = tolower(x);
return x =='a' x== 'e' x=='i' x=='o' x=='u' ;
}

string reverseVowels(string s) {
int L = -1,R = s.size(),n =s.size();
while(L < R){
while(!isVowels(s[++L]) && L < R);
while(!isVowels(s[--R]) && R > L);
if(L >= R) break;
swap(s[L], s[R]);
}
return s;
}
};

 

PS:本来不想写题解的,昨天那题太水了= =不过今天又出了一道类似的水题,就一起写了吧

本题是leetcode 344 Reverse String 和 345 Reverse Vowels of a String  题解,

更多题解可以查看:https://www.hrwhisper.me/leetcode-algorithm-solution/

请我喝杯咖啡吧~