gpt4 book ai didi

php - 如何从字符串中找到第一个非重复字符?

转载 作者:可可西里 更新时间:2023-11-01 13:36:05 25 4
gpt4 key购买 nike

我花了半天时间想弄清楚这个问题,最后我找到了可行的解决方案。但是,我觉得这可以用更简单的方式完成。我认为这段代码不太可读。

问题:从字符串中找到第一个不重复的字符。

$string = "abbcabz"

在这种情况下,函数应该输出“c”。

我使用连接而不是 $input[index_to_remove] = '' 的原因为了从给定的字符串中删除字符是因为如果我这样做,它实际上只会留下空单元格,这样我的返回值 $input[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];
}

最佳答案

<?php
// In an array mapped character to frequency,
// find the first character with frequency 1.
echo array_search(1, array_count_values(str_split('abbcabz')));

关于php - 如何从字符串中找到第一个非重复字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2955586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com