Post

Created by @nathanedwards
 at November 1st 2023, 5:59:31 am.

AP Computer Science Exam Question - String Manipulation

Problem Description:

You are given a string s consisting of lowercase alphabets. You need to implement the following two methods:

  1. 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.

  2. 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.

Example:

Input:

String s = "hello world";

Output for reverseVowels:

"holle werld"

Output for consecutiveDuplicates:

"helo world"

Constraints:

  • The input string s will only contain lowercase alphabets.
  • The length of the string s will be at most 10^5.

Explanation:

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.

  1. Initialize two pointers, start and end, pointing to the first and last characters of the string s, respectively.
  2. While start < end, perform the following steps:
    • Check if the character at index start is a vowel. If not, increment start by 1.
    • Check if the character at index end is a vowel. If not, decrement end by 1.
    • If both 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.

  1. Initialize an empty string result to store the final output.
  2. Iterate through the characters of the string s starting from index 0.
  3. Check if the current character is equal to the next character. If they are equal, skip to the next iteration.
  4. If they are not equal, append the current character to the result string.
  5. After the loop, return the result string.

The above steps will result in a string result with consecutive duplicates removed.

Complexity Analysis:

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.