DEV Community

özkan pakdil
özkan pakdil

Posted on

Algorithm question: reversing string with special characters

Given a string, that contains special character together with alphabets (‘a’ to ‘z’ and ‘A’ to ‘Z’), reverse the string such a way that special characters are not affected.

Example
input "abc-defg" return "gfe-dcba"

String reverse(String input) {
    Stack<Character> result = new Stack<>();
    StringBuilder result2 = new StringBuilder();
    char[] in = input.toCharArray();
    for (char c : in) {
        if (Character.isLetter(c)) {
            result.push(c);
        }
    }
    for (char c : in) {
        if (Character.isLetter(c)) {
            result2.append(result.pop());
        } else {
            result2.append(c);
        }
    }

    return result2.toString();
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay