我花了半天的時間試圖弄清楚這一點,最後我得到了工作解決方案。 但是,我覺得這可以用更簡單的方式完成。 我認爲這段代碼不是真正可讀的。如何從字符串中找到第一個不重複的字符?
問題:從字符串中查找第一個不重複的字符。
$字符串= 「abbcabz」
在這種情況下,該函數應該輸出 「C」。
我使用並置而不是$input[index_to_remove] = ''
爲了從給定的字符串 刪除字符的原因是因爲如果我這樣做,它實際上只是留出空白單元格,這樣我 返回值$輸入[0]不不返回我想要返回的字符。
例如,
$str = "abc";
$str[0] = '';
echo $str;
這將輸出 「BC」
但實際上,如果我考,
var_dump($str);
它會給我:
string(3) "bc"
這裏我的意圖是:
Given: input
while first char exists in substring of input {
get index_to_remove
input = chars left of index_to_remove . chars right of index_to_remove
if dupe of first char is not found from substring
remove first char from input
}
return first char of input
代碼:
function find_first_non_repetitive2($input) {
while(strpos(substr($input, 1), $input[0]) !== false) {
$index_to_remove = strpos(substr($input,1), $input[0]) + 1;
$input = substr($input, 0, $index_to_remove) . substr($input, $index_to_remove + 1);
if(strpos(substr($input, 1), $input[0]) == false) {
$input = substr($input, 1);
}
}
return $input[0];
}
+1爲簡短 – whiskeysierra 2010-06-02 08:11:10
+2爲簡單,謝謝! – 2010-06-02 17:25:46