Leetcode 344-reverse String

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.