Reverse a String using Stack

Technology CommunityCategory: StacksReverse a String using Stack
VietMX Staff asked 3 years ago

The followings are the steps to reversing a String using Stack:

  1. String to char[].
  2. Create a Stack.
  3. Push all characters, one by one.
  4. Then Pop all characters, one by one and put into the char[].
  5. Finally, convert to the String.
Complexity Analysis
Implementation
public static String reverse(String str) {
    char[] charArr = str.toCharArray();
    int size = charArr.length;
    Stack stack = new Stack(size);

    int i;
    for (i = 0; i < size; ++i) {
        stack.push(charArr[i]);
    }

    for (i = 0; i < size; ++i) {
        charArr[i] = stack.pop();
    }

    return String.valueOf(charArr);
}