• 345. Reverse Vowels of a String【easy】


    345. Reverse Vowels of a String【easy】

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

     解法一:

     1 class Solution {
     2 public:
     3     bool isVowels(char x) 
     4     {
     5         if (x >= 'A' && x <= 'Z') {
     6             x += 32;
     7         }
     8         return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u'); 
     9     }
    10     
    11     void reverseChar(string &s, int start, int end)
    12     {
    13         char temp = s[start];
    14         s[start] = s[end];
    15         s[end] = temp;
    16     }
    17     
    18     string reverseVowels(string s) {
    19         int start = 0;
    20         int end = s.length() - 1;
    21         
    22         while (start < end) {
    23             while (start < end && !isVowels(s[start])) {
    24                 ++start;
    25             }
    26             
    27             while (start < end && !isVowels(s[end])) {
    28                 --end;
    29             }
    30             
    31             reverseChar(s, start, end);
    32             ++start;
    33             --end;
    34         }
    35         
    36         return s;
    37     }
    38 };

    注意循环的条件

     
    解法二:
     1 class Solution {
     2 public:
     3     string reverseVowels(string s) {
     4         int i = 0, j = s.size() - 1;
     5         while (i < j) {
     6             i = s.find_first_of("aeiouAEIOU", i);
     7             j = s.find_last_of("aeiouAEIOU", j);
     8             if (i < j) {
     9                 swap(s[i++], s[j--]);
    10             }
    11         }
    12         return s;
    13     }
    14 };

    参考@tedbear 的代码。

  • 相关阅读:
    Sublime Text 无法使用Package Control或插件安装失败的解决方法
    phpstorm破解
    require
    在线支付
    解决华为手机用rem单位,内容超出屏幕宽度问题
    JS如何判断是不是iphoneX
    iPhoneX页面安全区域与内容重叠问题
    .NET 大数据量并发解决方案
    js 弹出div窗口 可移动 可关闭
    colgroup 整行变色
  • 原文地址:https://www.cnblogs.com/abc-begin/p/7583477.html
Copyright © 2020-2023  润新知