What should be the best approach when it comes to time & space complexity? Approach 1 or 2?
Approach 1:
Stack<Character> st = new Stack<Character>();
for (int i = 0; i < str.length(); ++i) {
if (str.charAt(i) != ' ')
st.push(str.charAt(i));
else {
while (st.empty() == false) {
System.out.print(st.pop());
}
System.out.print(" ");
}
}
while (st.empty() == false) {
System.out.print(st.pop());
}
Approach 2:
String welcomeString = "Welcome to Zscaler";
String removeSpace[] = welcomeString.split(" ");
String reversedString = "";
for (int i = 0; i < removeSpace.length; i++) {
String getString = removeSpace[i];
reversedString = "";
for (int j = getString.length() - 1; j >= 0; j--) {
reversedString = reversedString + getString.charAt(j);
}
System.out.print(reversedString + " ");
}