声明:
今天是第78道题。编写一个函数,以字符串作为输入,反转该字符串中的元音字母。以下所有代码经过楼主验证都能在LeetCode上执行成功,代码也是借鉴别人的,在文末会附上参考的博客链接,如果侵犯了博主的相关权益,请联系我删除
(手动比心ღ( ´・ᴗ・` ))
正文
题目:编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例 1:
复制代码1
2输入: "hello" 输出: "holle"示例 2:
复制代码1
2输入: "leetcode" 输出: "leotcede"
说明:
元音字母不包含字母"y"。
解法1。用对撞指针的思想,一左一右,如果指向的当前元素不是元音字母,就跳过,反之两者交换后继续遍历。
执行用时: 156 ms, 在Reverse Vowels of a String的Python提交中击败了47.32% 的用户
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ l = 0 r = len(s)-1 s = list(s) vowel = ['a','e','i','o','u','A','E','I','O','U'] while l < r: if s[l] not in vowel: l += 1 continue if s[r] not in vowel: r += 1 continue s[l],s[r] = s[r],s[l] l += 1 r -= 1 # 注意这里是减号,别顺手写错了 return ''.join(s)
解法2。更加pythonic的简洁代码,用一个stack存储s中出现过的元音字母,然后在返回结果时如果是元音就用stack的最后一个元素代替,代码如下。
执行用时: 288 ms, 在Reverse Vowels of a String的Python提交中击败了8.17% 的用户
复制代码
1
2
3
4
5
6
7
8
9class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ vowel = ['a','e','i','o','u','A','E','I','O','U'] stack = [i for i in s if i in vowel] return ''.join([i if i not in vowel else stack.pop() for i in s])
结尾
解法1&解法2:https://blog.csdn.net/qq_17550379/article/details/80515302
最后
以上就是彩色大山最近收集整理的关于【LeetCode 简单题】78-反转字符串中的元音字母声明:正文结尾的全部内容,更多相关【LeetCode内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复