zoukankan      html  css  js  c++  java
  • 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 的代码。

  • 相关阅读:
    微信多业务
    jps命令
    三白话经典算法系列 Shell排序实现
    无法识别的属性“targetFramework”。请注意,属性名是大写和小写。错误的解决方案
    Timus 1777. Anindilyakwa 奇怪的问题计数
    tokumx经营报表
    Quartz CronTrigger应用
    HDU 3681 BFS&amp;像缩进DP&amp;二分法
    01背包问题
    Web模板
  • 原文地址:https://www.cnblogs.com/abc-begin/p/7583477.html
Copyright © 2011-2022 走看看