-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseVowelsOfString.java
72 lines (59 loc) · 1.86 KB
/
ReverseVowelsOfString.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
------------------------------------------------------------------------------
345. Reverse Vowels of a String
------------------------------------------------------------------------------
Write a function that takes a string as input and reverse only the vowels of a string.
---------------------------------------
Example:
---------------------------------------
Example 1:
Given s = "hello", return "holle"
Example 2:
Given s = "leetcode", return "leotcede"
Hint : Use two Pointers
------------------------------------------------------------------------------
Problem Page : https://leetcode.com/problems/reverse-vowels-of-a-string/
Discussion/Approach : https://discuss.leetcode.com/category/429/reverse-vowels-of-a-string
Run Online : http://ideone.com/pGiW0D
------------------------------------------------------------------------------
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class ReverseVowelsOfString
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("leetcode = " + reverseVowels("leetcode"));
}
public static String reverseVowels(String inputString)
{
StringBuffer result = new StringBuffer(inputString);
int p1 = 0;
int p2 = inputString.length() - 1;
while(p1 < p2)
{
if(!isVowel(inputString.charAt(p1)))
{
p1++;
}
if(isVowel(inputString.charAt(p1)) && isVowel(inputString.charAt(p2)))
{
char c1 = inputString.charAt(p1);
char c2 = inputString.charAt(p2);
result.setCharAt(p1++,c2);
result.setCharAt(p2--,c1);
}
if(!isVowel(inputString.charAt(p2)))
{
p2--;
}
}
return result.toString();
}
private static boolean isVowel(char c)
{
String vowels = "aeiouAEIOU";
return (vowels.contains(""+c));
}
}