码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode.345 | Reverse Vowels of a String

时间:2020-08-06 09:30:08      阅读:64      评论:0      收藏:0      [点我收藏+]

标签:list   hello   leetcode   note   UNC   ring   only   tput   ever   

Leetcode.345 Reverse Vowels of a String

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

Example 1:

Input: "hello"
Output: "holle"

Example 2:

Input: "leetcode"
Output: "leotcede"

Note:
The vowels does not include the letter "y".

Solution

class Solution:
    def reverseVowels(self, s: str) -> str:
        s = list(s)
        vowels = (‘a‘,‘e‘,‘i‘,‘o‘,‘u‘)
        n = len(s)
        l = 0
        r = n - 1
        while l<r:
            while s[l].lower() not in vowels and l < n-1:
                l += 1 
            while s[r].lower() not in vowels and r > 0:
                r -= 1
            if l >= r:
                break
            
            s[l] = chr(ord(s[l]) ^ ord(s[r]))
            s[r] = chr(ord(s[l]) ^ ord(s[r]))
            s[l] = chr(ord(s[l]) ^ ord(s[r]))
            # s[l],s[r] = s[r],s[l]
            
            l += 1
            r -= 1
        return "".join(s)

Leetcode.345 | Reverse Vowels of a String

标签:list   hello   leetcode   note   UNC   ring   only   tput   ever   

原文地址:https://www.cnblogs.com/xm08030623/p/13444196.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!