---
# System prepended metadata

title: 345. Reverse Vowels of a String
tags: [LeetCode]

---

---
tags: 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".    

輸入範本如下
```C#
public class Solution {
    public string ReverseVowels(string s) {
        
    }
}
```

### 直覺想法
使用兩個指標 , 一個從頭開始 , 一個從尾開始 , 分別去找母音.
若找到則交換.

```C# 
104 ms	28.4 MB
You are here!
Your runtime beats 68.95 % of csharp submissions.
public string ReverseVowels(string s)
{
    char[] voewls = new char[] { 'a', 'e', 'i', 'o', 'u' };
    char[] charStr = s.ToCharArray();
    int left = 0, right = charStr.Length - 1;
    for (; left < right; left++, right--)
    {
        while (left < right && !voewls.Contains(char.ToLower(charStr[left]))) left++;
        while (left < right && !voewls.Contains(char.ToLower(charStr[right]))) right--;
        var temp = charStr[right];
        charStr[right] = charStr[left];
        charStr[left] = temp;

    }
    return new string(charStr);
}
```

槓 , 忘記查詢應該使用字典才對 , O(1) 的查詢時間
```C#
88 ms	27.1 MB
You are here!
Your runtime beats 97.87 % of csharp submissions.
public string ReverseVowels(string s)
{
     var voewls = new HashSet<char> { 'a', 'e', 'i', 'o', 'u' };
     char[] charStr = s.ToCharArray();
     int left = 0, right = charStr.Length - 1;
     for (; left < right; left++, right--)
     {
          while (left < right && !voewls.Contains(char.ToLower(charStr[left]))) left++;
          while (left < right && !voewls.Contains(char.ToLower(charStr[right]))) right--;
          var temp = charStr[right];
          charStr[right] = charStr[left];
          charStr[left] = temp;
     }
     return new string(charStr);
}
```










### Thank you! 

You can find me on

- [GitHub](https://github.com/s0920832252)
- [Facebook](https://www.facebook.com/fourtune.chen)

若有謬誤 , 煩請告知 , 新手發帖請多包涵

# :100: :muscle: :tada: :sheep: 
