I have a String and want to reverse it so that some characters get reversed, while others remain in place. How can I implement that (e.g. lets say I want all letters to reverse while all numbers stay in place)?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can create an automaton for it:
iterate over the string, insert each letter into the stack and replace it with a special character which is not in the original string (i.e. $), do not change digits at all.
iterate over the string again, replace every $ with the head of the stack.
note: since String is immutable you will need to first export it to a StringBuilder or CharSequence
EDIT
for example:
result will be
t45setgni1rtsacomplexity is O(n): iterating the string (twice) – since all stack operations are O(1).