File tree Expand file tree Collapse file tree 1 file changed +41
-1
lines changed
Expand file tree Collapse file tree 1 file changed +41
-1
lines changed Original file line number Diff line number Diff line change 11package MustDoEasyList ;
22
3+ import java .util .Arrays ;
4+
35public class ReverseWordsInAStringIII557 {
46
57 public static String reverseWords (String s ) {
@@ -30,7 +32,45 @@ private static String reverseOneWord(String word) {
3032 return ans .toString ();
3133 }
3234
35+ // second approach
36+ public static String reverseWords2 (String s ) {
37+ int len = s .length ();
38+ char [] arr = s .toCharArray ();
39+
40+ int firstidx = 0 , lastidx = 0 ;
41+
42+ for (int i = 0 ; i < len ; i ++) {
43+
44+ if (arr [i ] == ' ' ) {
45+ lastidx = i - 1 ;
46+ reverseHelper (arr , firstidx , lastidx );
47+ firstidx = i + 1 ;
48+ }
49+ }
50+
51+ // now last word is left to be reversed
52+ reverseHelper (arr , firstidx , len - 1 );
53+
54+ return new String (arr );
55+ }
56+
57+ private static void reverseHelper (char [] arr , int firstidx , int lastidx ) {
58+ while (firstidx < lastidx ) {
59+ char temp = arr [firstidx ];
60+ arr [firstidx ] = arr [lastidx ];
61+ arr [lastidx ] = temp ;
62+ firstidx ++;
63+ lastidx --;
64+ }
65+ }
66+
3367 public static void main (String [] args ) {
34- System .out .println (reverseWords ("hello world" ));
68+ System .out .println (reverseWords2 ("hello world" ));
3569 }
3670}
71+
72+ /*
73+ * Input: s = "Let's take LeetCode contest"
74+ *
75+ * Output: "s'teL ekat edoCteeL tsetnoc"
76+ */
You can’t perform that action at this time.
0 commit comments