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

posted on 2012-09-29 17:55  ZimZz  阅读(1032)  评论(0编辑  收藏  举报