1 <?php 2 #顛倒字串 3 4 #將字串從頭和尾向中間遍曆,交換位置 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 #逆轉句子,但不逆轉單詞18 19 #第一種方法,先將句子整個逆轉,再將單詞逐個逆轉,複雜度為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 #遇到空格即為一個單詞,將該單詞逆轉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 #第二種方法,每次遇到空格即為一個單詞,將該單詞入棧,然後依次出棧,時間複雜度為O(n),空間複雜度為O(n),其中k為單詞數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