小凉

3 0642700 3 0642770 5 34202 13942 4314 0624

字符串旋转

题目:Reverse String (难度一颗星)

Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".

实现:

 1 class Solution {
 2 public:
 3     string reverseString(string s) {
 4         int length = s.length();
 5         int start = 0;
 6         int ends = length - 1;
 7         while(start < ends)
 8         {
 9             int temp = s[start];
10             s[start] = s[ends];
11             s[ends] = temp;
12             start++;
13             ends--;
14         }
15         return s;
16     }
17 };

 

题目: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".

 

实现:

 1 class Solution {
 2 public:
 3     bool validate(char c)
 4   {
 5         return (c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u') || (c == 'A') || (c == 'E') || (c == 'I') || (c == 'O') || (c == 'U');
 6   }
 7     
 8     string reverseVowels(string s) {
 9         int starts = 0;
10         int ends = s.size()-1;
11         while (starts < ends)
12     {
13             while (!validate(s[starts]))
14       {
15                 starts++;
16       }
17             while (!validate(s[ends]))
18       {
19                 ends--;
20       }
21             if (starts > ends)
22       {
23                 break;
24       }
25             int temp = s[starts];
26             s[starts] = s[ends];
27             s[ends] = temp;
28             starts++;
29             ends--;
30   }
31         return s;
32 }
33 };

 

 

 

posted on 2016-05-05 16:33  小凉  阅读(194)  评论(0编辑  收藏  举报

导航