Approach: The solution iterates through each character of the input string and appends only non-whitespace characters to a StringBuilder. The Character.isWhitespace() method is used to identify spaces, tabs, and other whitespace characters.
Using StringBuilder avoids creating multiple intermediate String objects and provides an efficient solution for large inputs.
Java Solution:
public class RemoveWhiteSpaces {
public static String removeWhiteSpaces(String input) {
StringBuilder result = new StringBuilder();
for (int index = 0; index < input.length(); index++) {
char currentCharacter = input.charAt(index);
if (!Character.isWhitespace(currentCharacter)) {
result.append(currentCharacter);
}
}
return result.toString();
}
public static void main(String[] args) {
String input = "Java Interview Kit Application";
String output = removeWhiteSpaces(input);
System.out.println("Original String: " + input);
System.out.println("String Without White Spaces: " + output);
}
}Output: Original String: Java Interview Kit Application String Without White Spaces: JavaInterviewKitApplication
Time Complexity: O(n), where n is the length of the input string because each character is processed exactly once.
Space Complexity: O(n), since a new StringBuilder is used to store the resulting string without whitespace characters.
Key Interview Points: • Character.isWhitespace() handles spaces, tabs, and other whitespace characters. • StringBuilder is preferred over String concatenation inside loops because it avoids creating unnecessary objects. • An alternative approach is to convert the string into a character array and shift non-whitespace characters in-place, but that increases implementation complexity with little benefit in most scenarios.