The original question is as follows:
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "Hello", Return "Olleh".
Simple string flipping, directly on the code.
1 Public string reversestring (string s) {2 New StringBuilder (); 3 for (int i = s.length ()-1; I >= 0; i--) {4 sb.append (S.charat (i)); 5 }6 return sb.tostring (); 7 }
How to achieve in-situ flip it? Because string cannot be modified, the method definition needs to be modified, and the parameter uses StringBuilder.
1 Public voidreversestringinplace (StringBuilder sb) {2Reversestringinplace (SB, 0, Sb.length ()-1);3 }4 5 Public voidReversestringinplace (StringBuilder SB,intStartintend) {6 if(Start >= End | | end > Sb.length ()-1) {7 return;8 }9 for(inti = start, j = end; I < J; i++, j--) {Ten CharTMP =Sb.charat (i); One Sb.setcharat (I, Sb.charat (j)); A Sb.setcharat (J, TMP); - } -}
Here's another question, how do you flip the order of words in a string, but the word itself doesn't change?
Example:
Given s = "Hello World" and return "World Hello".
WORKAROUND: Flip Each word first, then flip the entire string.
1 Public voidreversesentenceinplace (StringBuilder sb) {2 inti = 0, j = 0;3 for(; J < Sb.length (); j + +) {4 if(!Character.isletter (Sb.charat (j))) {5 if(I <j) {6Reversestringinplace (SB, I, j-1);7 }8i =J;9i++;Ten } One } A if(I <j) { -Reversestringinplace (SB, I, j-1); - } theReversestringinplace (SB, 0, Sb.length ()-1); -}
Reference Source: Https://github.com/pkufork/Martians/blob/master/src/main/java/com/pkufork/martians/leetcode/ReverseString344.java
Leetcode 344-reverse String