easy
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".
Given s = "hello", return "holle".
Example 2:
Given s = "leetcode", return "leotcede".
Given s = "leetcode", return "leotcede".
Note:
The vowels does not include the letter "y".
The vowels does not include the letter "y".
思路: convert to char array, use two pointer: i - track the vowel from begin; j - track the vowel from end
once both i & j point to vowel, swap char
public class Solution { public String reverseVowels(String s) { char[] word = s.toCharArray(); Set<Character> set = new HashSet<Character>(Arrays.asList('a','e','i','o','u','A','E','I','O','U')); int i = 0,j = word.length-1; while(i<j){ char a = word[i]; char b = word[j]; if(!set.contains(a)){ i++; }else if(!set.contains(b)){ j--; }else{//a & b both vowel word[i] = b; word[j] = a; i++; j--; } } return new String(word); } }
304, simply reverse string
思路: use two pointer i from start, j from end, keep swaping i++, j-- while i < j
public class Solution { public String reverseString(String s) { char[] word = s.toCharArray(); int i = 0,j = word.length-1; while(i<j){ char tmp = word[i]; word[i] = word[j]; word[j] = tmp; i++; j--; } return new String(word); } }
No comments:
Post a Comment