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