You are given a string s
consisting of lowercase alphabets. You need to implement the following two methods:
reverseVowels(String s)
: This method takes a string as input and returns a new string where only the vowels in the original string are reversed.
consecutiveDuplicates(String s)
: This method takes a string as input and returns a new string where consecutive duplicates in the original string are removed.
You must implement both methods in a class called StringManipulator
.
public class StringManipulator {
public static String reverseVowels(String s) {
// implementation goes here
}
public static String consecutiveDuplicates(String s) {
// implementation goes here
}
}
Complete the implementation of both methods and provide step-by-step explanations.
Input:
String s = "hello world";
Output for reverseVowels
:
"holle werld"
Output for consecutiveDuplicates
:
"helo world"
s
will only contain lowercase alphabets.s
will be at most 10^5.reverseVowels
method:To solve this problem, we need to iterate through the given string s
and reverse the vowels in the string while maintaining the positions of the consonants.
start
and end
, pointing to the first and last characters of the string s
, respectively.start
< end
, perform the following steps:
start
is a vowel. If not, increment start
by 1.end
is a vowel. If not, decrement end
by 1.start
and end
point to vowels, swap the characters and increment start
by 1 and decrement end
by 1.The above steps will result in a reversed string s
with only the vowels reversed.
consecutiveDuplicates
method:To solve this problem, we need to iterate through the given string s
and remove consecutive duplicates.
result
to store the final output.s
starting from index 0.result
string.result
string.The above steps will result in a string result
with consecutive duplicates removed.
The time complexity for both reverseVowels
and consecutiveDuplicates
methods is O(n), where n is the length of the input string s
. This is because we iterate through the string once to perform the required operations.
The space complexity for both methods is O(n), as we are using an additional string result
to store the final output.