PHP 逆轉字串與逆轉句子

來源:互聯網
上載者:User
 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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.