题目链接: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".
思路:
easy
算法:
public String reverseVowels(String s) { char c[] = s.toCharArray(); Set<String> vowels = new HashSet<String>(); vowels.add("a"); vowels.add("e"); vowels.add("i"); vowels.add("o"); vowels.add("u"); vowels.add("A"); vowels.add("E"); vowels.add("I"); vowels.add("O"); vowels.add("U"); int v1=-1,v2=-1; for(int start=0,end=c.length-1;start<end;){ if(v1==-1){ if(vowels.contains(c[start]+"")) v1 = start; else start++; } if(v2==-1){ if(vowels.contains(c[end]+"")) v2 = end; else end--; } if(v1!=-1&&v2!=-1){ char tmp = c[v1]; c[v1] = c[v2]; c[v2] = tmp; v1 = -1; v2 = -1; start++; end--; } } return new String(c); }
时间: 2024-10-11 01:50:48