如何从字符串中查找第一个非重复字符? [英] How to find first non-repetitive character from a string?

查看:159
本文介绍了如何从字符串中查找第一个非重复字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了半天的时间试图弄清楚这一点,终于找到了可行的解决方案. 但是,我觉得这可以通过更简单的方式来完成. 我认为这段代码不太可读.

I've spent half day trying to figure out this and finally I got working solution. However, I feel like this can be done in simpler way. I think this code is not really readable.

问题:从字符串中查找第一个非重复字符.

Problem: Find first non-repetitive character from a string.

$ string ="abbcabz"

$string = "abbcabz"

在这种情况下,该函数应输出"c".

In this case, the function should output "c".

我使用串联而不是$input[index_to_remove] = ''的原因 为了从给定的字符串中删除字符 是因为如果我这样做,实际上只会留下一个空单元格,这样我 返回值$ input [0]不返回我要返回的字符.

The reason I use concatenation instead of $input[index_to_remove] = '' in order to remove character from a given string is because if I do that, it actually just leave empty cell so that my return value $input[0] does not not return the character I want to return.

例如

$str = "abc";
$str[0] = '';
echo $str;

这将输出"bc"

但是实际上,如果我测试

But actually if I test,

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')));

这篇关于如何从字符串中查找第一个非重复字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆