345. Reverse Vowels of a String

Leetcode

https://leetcode.com/problems/reverse-vowels-of-a-string/

題目

Given a string s, reverse only all the vowels in the string and return it.

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases.

解答

  • 方法一

var reverseVowels = function(s) {
    const vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
    
    let left = 0;
    let right = s.length - 1;
    const swap = (i, j) => {
        s = s.substring(0, i) + s[j] + s.substring(i+1, j) + s[i] + s.substring(j+1)
    }
    while(true) {
      while(!vowels.includes(s[left]) && left < right) {
        left++;
      }
      while(!vowels.includes(s[right]) && left < right) {
        right--;
      }
      if(left >= right) break;
      swap(left, right);
      left++;
      right--;
    }
    
    return s;
};

Runtime: 505 ms, faster than 5.19% of JavaScript online submissions for Reverse Vowels of a String.

Memory Usage: 65.3 MB, less than 5.19% of JavaScript online submissions for Reverse Vowels of a String.

  • 方法二

var reverseVowels = function(s) {
    const vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
    
    let left = 0;
    let right = s.length - 1;
    const arr = s.split('');
    while(true) {
      while(!vowels.includes(arr[left]) && left < right) {
        left++;
      }
      while(!vowels.includes(arr[right]) && left < right) {
        right--;
      }
      if(left >= right) break;
      // swap the element of array
      [arr[left], arr[right]] = [arr[right],arr[left]];
      left++;
      right--;
    }
    
    return arr.join('');
};

Runtime: 127 ms, faster than 40.45% of JavaScript online submissions for Reverse Vowels of a String.

Memory Usage: 44.2 MB, less than 75.85% of JavaScript online submissions for Reverse Vowels of a String.

測資

let s = "hello";
s = "leetcode";
s = ".,";

console.log(reverseVowels(s))

Last updated

Was this helpful?