1 <? PHP 2 # reverse string 3 4 # traverse the string from the beginning and end to the center, switching position 5 function cstrrev (& $ STR, $ begin, $ Len) {6 $ I = $ begin; 7 $ J = $ begin + $ len-1; 8 while ($ I <$ J) {9 $ temp = $ STR [$ I]; 10 $ STR [$ I] = $ STR [$ J]; 11 $ STR [$ J] = $ temp; 12 $ I ++; 13 $ j --; 14} 15} 16 17 # reverse the sentence, but do not reverse the word 18 19 # The first method is to first reverse the entire sentence, then, words are reversed one by one. The complexity is O (2n) 20 function sentence_rev (& $ s) {21 cstrrev ($ S, 0, strlen ($ s )); 22 $ I = 0; 23 $ J = 0; 24 while ($ j <strlen ($ s) {25 # encounter Spaces Is a word, which is reversed by 26 if ($ s [$ J] = "" | $ J = strlen ($ S)-1) {27 cstrrev ($ S, $ I, $ J-$ I); 28 $ I = $ J + 1; 29} 30 $ J ++; 31} 32} 33 34 # method 2. Each time a space is entered, the word is written into the stack and then output to the stack in sequence. The time complexity is O (n ), the space complexity is O (n), where k is the number of words 35 function sentence_rev2 ($ s) {36 $ stack = array (); 37 $ word = ""; 38 $ I = 0; 39 while ($ I <strlen ($ s) {40 if ($ I = strlen ($ S)-1) {41 $ word. = $ s [$ I]; 42 array_push ($ stack, $ word); 43} 44 if ($ s [$ I] = ""){ 45 array_push ($ stack, $ word); 46 $ word = ""; 47} else {48 $ word. = $ s [$ I]; 49} 50 $ I ++; 51} 52 53 $ sr = ""; 54 while (! Empty ($ stack) {55 $ Sr. = array_pop ($ stack ). ""; 56} 57 58 return substr ($ Sr, 0, strlen ($ SR)-1); 59} 60 61 $ STR = "abcdefg "; 62 cstrrev ($ STR, 0, strlen ($ Str); 63 echo $ Str. "<br>"; 64 $ S = "I am Alexis"; 65 sentence_rev ($ S); 66 echo $ S. "<br>"; 67 $ S2 = sentence_rev2 ("You are not Alexis"); 68 echo $ S2; 69?>
Gfedcba
Alexis am I
Alexis not are you