Leetcode557 Reverse Words in a String III Java implementation

Source: Internet
Author: User

This time to try split a string is good with split, or manually find index after substring good. Because the strong brother said Leetcode on the run time is not stable, sometimes may be 50% of the speed is much worse!

Method 1,split:

 Public classReverseWordsInAStringIII557 { Publicstring Reversewords (string s) {string[] words=GetWordsv1 (s); StringBuilder result=NewStringBuilder (); BooleanIsFirst =true;  for(String word:words) {StringBuilder sb=Reverseword (word); if(isFirst) {IsFirst=false;            Result.append (SB); }            Else{result.append (" ");            Result.append (SB); }        }        returnresult.tostring (); }     Public Staticstring[] GetWordsv1 (String s) {string[] words= S.split (""); returnwords; }     PublicStringBuilder Reverseword (String s) {Char[] Letters =S.tochararray (); intLen =letters.length;  for(intI =0;i<len/2;i++) {            Chartemp =Letters[i]; Letters[i]= letters[len-1-i]; Letters[len-1-i] =temp; } StringBuilder SB=NewStringBuilder ();        Sb.append (Letters); returnSB; }}

It's already pretty good. Try Method 2 below, manually:

Um...... Suddenly found that the String.IndexOf method cannot return all index, only the first and last, um ... Purely manual traversal of a wave? Give it a try.

Try to write the discovery to use ArrayList, because directly with int[] can not determine the length, the efficiency is certainly reduced.

So in the future, the problem of split indeterminate length is to use split bar, with a fixed length and a limited number of split can try a faster original method.

In addition to see discuss area This article is also good https://leetcode.com/problems/reverse-words-in-a-string-iii/discuss/101963/ easiest-java-solution-(9MS)-similar-to-reverse-words-in-a-string-ii

Leetcode557 Reverse Words in a String III Java implementation

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.