LeetCode #345 Reverse Vowels of a String
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode #345 Reverse Vowels of a String相关的知识,希望对你有一定的参考价值。
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".
维护首尾两个指针i和j,每次循环如果s[i]和s[j]都是vowel才交换,否则哪个不是vowel,就让i++或j--,直到i==j遍历完毕,时间复杂度O(N)
需要注意的是python中str是不能直接内部互换元素的,所以需要先转换成list,最后再join到一个空串返回
class Solution(object): def reverseVowels(self, s): res = list(s) vowels = [‘a‘, ‘e‘, ‘i‘, ‘o‘, ‘u‘] i = 0; j = len(s) - 1 while i < j: if res[i].lower() not in vowels: i += 1 elif res[j].lower() not in vowels: j -= 1 else: res[i],res[j] = res[j],res[i] i += 1 j -= 1 return "".join(res)
检查是否是vowel可以先创建vowel的list,再看是否in即可,不用再另外定义一个函数判断vowel
以上是关于LeetCode #345 Reverse Vowels of a String的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode #345 Reverse Vowels of a String
LeetCode 345. Reverse Vowels of a String
Leetcode 345. Reverse Vowels of a String
LeetCode_345. Reverse Vowels of a String