码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Reverse Vowels of a String

时间:2016-08-27 07:36:31      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里:https://leetcode.com/problems/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".

题解:

典型的two pointers, 到了vowel时对调.

Time Complexity: O(s.length()). Space:O(s.length()), 因为建立了char array.

AC Java:

 1 public class Solution {
 2     public String reverseVowels(String s) {
 3         HashSet<Character> hs = new HashSet<Character>();
 4         hs.add(‘A‘);
 5         hs.add(‘a‘);
 6         hs.add(‘E‘);
 7         hs.add(‘e‘);
 8         hs.add(‘I‘);
 9         hs.add(‘i‘);
10         hs.add(‘O‘);
11         hs.add(‘o‘);
12         hs.add(‘U‘);
13         hs.add(‘u‘);
14         
15         char [] charArr = s.toCharArray();
16         int i = 0;
17         int j = charArr.length-1;
18         while(i<j){
19             while(i<j && !hs.contains(charArr[i])){
20                 i++;
21             }
22             while(i<j && !hs.contains(charArr[j])){
23                 j--;
24             }
25             if(i<j){
26                 swap(charArr, i, j);
27                 i++;
28                 j--;
29             }
30         }
31         
32         return new String(charArr);
33      }
34      
35      private void swap(char [] arr, int i, int j){
36          char temp = arr[i];
37          arr[i] = arr[j];
38          arr[j] = temp;
39      }
40 }

 

LeetCode Reverse Vowels of a String

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/5812211.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!