leetcode 344|345|541. Reverse String 1|2 345. Reverse Vowels of a String

来源:互联网 发布:淘宝助理下载订单很慢 编辑:程序博客网 时间:2024/06/05 05:49

344. Reverse String

Write a function that takes a string as input and returns the string reversed.

Example:
Given s = "hello", return "olleh".

class Solution {public:    string reverseString(string s)     {        //way-1        /*        reverse(s.begin(), s.end());        return s;            */                //way-2        int i = 0;        int j = s.size() - 1;        while (i < j)        {            swap(s[i], s[j]);            i++;            j--;        }        return s;    }};


541. Reverse String II

Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.

Example:

Input: s = "abcdefg", k = 2Output: "bacdfeg"

Restrictions:
  1. The string consists of lower English letters only.
  2. Length of the given string and k will in the range [1, 10000]

class Solution {public:    string reverseStr(string s, int k)     {        int pos = 0;        while ( pos < s.size() )        {            my_reverse(s, pos, k);            pos = pos + 2 * k;        }        return s;        }        void my_reverse(string& s, int pos, int len)    {        if (pos + len >= s.size())        {            string r = s.substr(pos);            reverse(r.begin(), r.end());            s = s.substr(0, pos) + r;        }        else        {            string r = s.substr(pos, len);            reverse(r.begin(), r.end());            s = s.substr(0, pos) + r + s.substr(pos + len);        }    } };


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:
Given s = "hello", return "holle".

Example 2:
Given s = "leetcode", return "leotcede".

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

class Solution {public:    string reverseVowels(string s)     {        int i = 0;         int j = s.size() - 1;        while (i < j)        {            while (i < j && !isvowel(s[i]))                i++;            while (i < j && !isvowel(s[j]))                j--;            swap(s[i++], s[j--]);        }        return s;    }    bool isvowel(char k)    {        return  k == 'a' || k == 'e' || k == 'i' || k == 'o' || k == 'u' ||                 k == 'A' || k == 'E' || k == 'I' || k == 'O' || k == 'U';    }};



原创粉丝点击