Swap Corner Words and Reverse Middle Characters in Java
The task of "swap corner words and reverse middle characters in Java" involves manipulating a given string by swapping the first and last words and reversing the characters in the middle word. This task can be broken down into several steps, including splitting the string into words, performing the necessary swaps and reversals, and then reconstructing the modified string.
Approach 1: Using substring and StringBuilder
In this approach we get involved in using the substring method and a StringBuilder to swap the corner words and reverse the characters in the middle word of a given string. The approach is straightforward and efficient, and it leverages the StringBuilder class to efficiently reverse the characters in the middle word.
Algorithm
Step 1: Define a static method named swapAndReverse that takes a single String parameter (input) for string manipulation.
Step 2: Use the split(" ") method to split the input string into an array of words. Store this array in a variable named words.
Step 3: Swap the positions of the first and last words in the words array: Store the first word (words[0]) in a temporary variable (temp). Replace words[0] with the last word (words[words.length - 1]). Replace words[words.length - 1] with the value stored in the temporary variable.
Step 4: Reversing Middle Words
Step 4.1: Initialize an empty string (reversedMiddle) to store reversed middle words. Iterate through the array of words from the second-to-last word to the second word.
Step 4.2: For each middle word, reverse its characters using a StringBuilder. Append the reversed middle word to the reversedMiddle string with a space.
Step 5: Print the original input string and the modified string with swapped corner words and reversed middle characters:
Step 5.1: Display the original string using System.out.println("Original String: " + input).
Step 5.2: Display the modified string by concatenating the first word, reversed middle words, and the last word. Print the result using System.out.println("Modified String: " + words[0] + " " + reversedMiddle + words[words.length - 1]).
Step 6: Inside the main method, create a custom input string (e.g., "Hello World Happy New Year"). Call the swapAndReverse method with the custom input string as an argument. The original and modified strings are displayed as output.
Filename: StringManipulation.java
public class StringManipulation {
static void swapAndReverse(String input) {
// Split the input string into words
String[] words = input.split(" ");
// Swap the first and last words
String temp = words[0];
words[0] = words[words.length - 1];
words[words.length - 1] = temp;
// Initialize string for reversed middle words
String reversedMiddle = "";
// Reverse the characters in all middle words
for (int i = words.length - 2; i >= 1; i--) {
StringBuilder middleWord = new StringBuilder(words[i]);
reversedMiddle += middleWord.reverse().toString() + " ";
}
// Display the original and modified strings
System.out.println("Original String: " + input);
System.out.println("Modified String: " + words[0] + " " + reversedMiddle + words[words.length - 1]);
}
public static void main(String[] args) {
// Custom input string
String inputString = "Hello World Happy New Year";
// Call the method with the custom input string
swapAndReverse(inputString);
}
}
Output:
Original String: Hello World Happy New Year
Modified String: Year weN yppaH dlroW Hello
Time Complexity
The time complexity of this algorithm is O(n), where n is the length of the input string. The primary operations involve splitting the string, swapping words, reversing characters in the middle word, and joining the words back into a string. Each of these operations has a linear time complexity relative to the length of the input string.
Space Complexity
The space complexity is O(n), where n is the length of the input string. The algorithm uses additional space for the array of words, the temporary variables, and the StringBuilder objects for reversing characters. The space required is proportional to the length of the input string.
Approach 2: Iterative Approach
The iterative approach used in the provided Java code aims to swap the first and last words of a given string and reverse the characters in the middle portion. This approach employs simple string manipulation techniques and iterative traversals through the characters of the input string.
Algorithm
Step 1: Define a static method named customSwap that takes two parameters: a String named input and an integer len representing the length of the string.
Step 2: Initialize three empty strings: firstWord, lastWord, and middleWords to store the first word, last word, and reversed middle words, respectively. Initialize an integer variable index to iterate through the characters in the input string.
Step 3: Use a loop to find the characters of the first word in the input string until a space (' ') is encountered. Store the first word in the lastWord string.
Step 4: Initialize another integer variable index1 to iterate from the end of the input string. Use a loop to find the characters of the last word in the input string until a space (' ') is encountered. Store the last word in the firstWord string.
Step 5: Initialize a loop from index1 - 1 to index. For each character in the middle words, check for a space and add a space to the middleWords string. Otherwise, add the character to middleWords.
Step 6: Print the original input string using System.out.println("Original String: " + input). Print the modified string by concatenating the first word, reversed middle words, and the last word. Print the result using System.out.println("Modified String: " + firstWord + " " + middleWords + " " + lastWord).
Step 7: Inside the main method, create a custom input string (e.g., "Hello World Happy New Year"). Call the customSwap method with the custom input string and its length as arguments.
Filename: IterativeStingManipulation.java
import java.util.*;
public class IterativeStringManipulation {
static void customSwap(String input, int len) {
String firstWord = "";
String lastWord = "";
int index = 0;
// Find the first word
for (index = 0; index < len; ++index) {
if (input.charAt(index) == ' ') {
break;
}
lastWord += input.charAt(index);
}
int index1 = 0;
// Find the last word
for (index1 = len - 1; index1 >= 0; --index1) {
if (input.charAt(index1) == ' ') {
break;
}
firstWord = input.charAt(index1) + firstWord;
}
String middleWords = "";
for (int i = index1 - 1; i > index; --i) {
if (input.charAt(i) == ' ') {
middleWords += " ";
} else {
middleWords += input.charAt(i);
}
}
// Display the original and modified strings
System.out.println("Original String: " + input);
System.out.println("Modified String: " + firstWord + " " + middleWords + " " + lastWord);
}
public static void main(String[] args) {
// Custom input string
String inputString = "Hello World Happy New Year";
// Calculating string length using length() method
// and storing it in a variable
int length = inputString.length();
// Calling the custom method to swap the words
// for the custom input string
customSwap(inputString, length);
}
}
Output:
Original String: Hello World Happy New Year
Modified String: Year weN yppaH dlroW Hello
Time Complexity
The time complexity of the provided iterative approach is O(n), where n is the length of the input string. The algorithm iterates through the string once, performing operations that take constant time for each character.
Space Complexity
The space complexity is O(n), where n is the length of the input string. Additional space is used to store the first, last, and middle string variables, and the space required is proportional to the length of the input string.
Approach 3: Using ArrayList
The approach using ArrayList introduces a flexible and dynamic data structure to store and manipulate the words of the input string. Unlike arrays with a fixed size, ArrayList in Java can dynamically grow or shrink, providing more flexibility when working with collections of elements. This approach leverages the benefits of ArrayList to simplify the manipulation of words during the swapping and reversing process.
Algorithm
Step 1: Split the input string into an ArrayList of words using space as the delimiter. Check if there are at least two words in the ArrayList. If not, return the original string as there are not enough words for modification.
Step 2: Swap First and Last Words: If there are only two words, simply swap them. If there are more than two words, swap the positions of the first and last words.
Step 3: Swap the positions of middle words (excluding the first and last) in the ArrayList. Iterate over the middle words (excluding the first and last) in the ArrayList. For each middle word, reverse its characters using StringBuilder.
Step 4: Join the modified words back into a string using space as the separator. Return the modified string.
Filename: ArrayListApproach.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class ArrayListApproach {
// Method to swap corner words and reverse middle characters using ArrayList
static String swapAndReverse(String input) {
// Split the input string into an ArrayList of words
ArrayList<String> wordList = new ArrayList<>(Arrays.asList(input.split(" ")));
// Check if there are at least two words
if (wordList.size() >= 2) {
// If there are only two words, simply swap them
if (wordList.size() == 2) {
Collections.swap(wordList, 0, 1);
} else {
// Swap the first and last words
Collections.swap(wordList, 0, wordList.size() - 1);
// Swap the positions of middle words (excluding first and last)
int middleStart = 1;
int middleEnd = wordList.size() - 2;
Collections.swap(wordList, middleStart, middleEnd);
// Reverse the characters in all middle words using StringBuilder
for (int i = 1; i < wordList.size() - 1; i++) {
String middleWord = wordList.get(i);
StringBuilder reversedMiddle = new StringBuilder(middleWord).reverse();
wordList.set(i, reversedMiddle.toString());
}
}
// Join the modified words back into a string
return String.join(" ", wordList);
} else {
// If there are not enough words, return the original string
return input;
}
}
// Main method
public static void main(String[] args) {
// Example usage with a custom input string
String inputString = "Hello World Happy New Year";
String result = swapAndReverse(inputString);
// Display the original and modified strings
System.out.println("Original String: " + inputString);
System.out.println("Modified String: " + result);
}
}
Output:
Original String: Hello World Happy New Year
Modified String: Year weN yppaH dlroW Hello
Time Complexity
The time complexity of the provided approach using ArrayList is O(n), where n is the number of words in the input string. The algorithm iterates through the wordList once, performing operations that take constant time for each word.
Space Complexity
The space complexity is O(n), where n is the number of words in the input string. Additional space is used for the wordList ArrayList, which stores the words from the input string. The space required is proportional to the number of words in the input string.
Approach 4: Using StringTokenizer
The approach using StringTokenizer is a method to tokenize or split a string into individual words. StringTokenizer is a class in Java that allows you to break a string into tokens based on a specified delimiter. This approach utilizes StringTokenizer to separate words in the input string and performs the required operations on these words, such as swapping the first and last words and reversing the characters in the middle words.
Algorithm
Step 1: Define a static method named swapAndReverse that takes a String parameter input. Use StringTokenizer to split the input string into words and count the number of words (wordCount).
Step 2: Check if there are at least two words (wordCount >= 2). If there are only two words, swap them and return the result. If more than two words, store the words in an array (words).
Step 3: Swap the first and last words. Swap the positions of middle words (excluding first and last). Reverse the characters in all middle words.
Step 4: Join the modified words back into a string using the String.join method and return the result. If false, return the original input string.
Step 5: In the main method, provide an example input string. Call the swapAndReverse method with the example input string. Display the original and modified strings.
Filename: StringTokenizerApproach.java
import java.util.StringTokenizer;
public class StringTokenizerApproach {
static String swapAndReverse(String input) {
// Use StringTokenizer to split the input string into words
StringTokenizer tokenizer = new StringTokenizer(input);
int wordCount = tokenizer.countTokens();
// Check if there are at least two words
if (wordCount >= 2) {
// If there are only two words, simply swap them
if (wordCount == 2) {
String firstWord = tokenizer.nextToken(); // get the first word
return tokenizer.nextToken() + " " + firstWord; // swap and return
}
// Store the words in an array
String[] words = new String[wordCount];
for (int i = 0; i < wordCount; i++) {
words[i] = tokenizer.nextToken();
}
// Swap the first and last words
String temp = words[0];
words[0] = words[wordCount - 1];
words[wordCount - 1] = temp;
// Swap the positions of middle words (excluding first and last)
int middleStart = 1;
int middleEnd = wordCount - 2;
String tempMiddle = words[middleStart];
words[middleStart] = words[middleEnd];
words[middleEnd] = tempMiddle;
// Reverse the characters in all middle words
for (int i = 1; i < wordCount - 1; i++) {
words[i] = new StringBuilder(words[i]).reverse().toString();
}
// Join the modified words back into a string
return String.join(" ", words);
} else {
// If there are not enough words, return the original string
return input;
}
}
public static void main(String[] args) {
// Example usage with a custom input string
String inputString = "Hello World Happy New Year";
String result = swapAndReverse(inputString);
// Display the original and modified strings
System.out.println("Original String: " + inputString);
System.out.println("Modified String: " + result);
}
}
Output:
Original String: Hello World Happy New Year
Modified String: Year weN yppaH dlroW Hello
Time Complexity
The StringTokenizer class has a time complexity of O(n), where n is the length of the input string. It linearly processes each character in the input string to identify and count the tokens. The overall time complexity for word retrieval and operations is O(w), where w is the total number of words in the input string. Overall, the dominant factor is the tokenization process, making the total time complexity O(n).
Space Complexity
Space required for words array: O(w), where w is the number of words in the input string. Space required for StringBuilder objects during character reversal: O(m), where m is the maximum length of a word. Additional space complexity for variables and temporary storage is negligible. Overall space complexity: O(w + m).
Conclusion
In conclusion, the task of swapping the corner words and reversing the middle characters in a Java string involves various approaches, each with its own advantages and considerations. The choice of approach can depend on the specific constraints and characteristics of the input data and also may prioritize readability, simplicity, or efficiency based on the context in which the code is used.