1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| 思路: 确定唯一的字符,在确认唯一字符的下标 或者使用array_count_values()直接获取数量,在使用strpos获取下标
代码: /** * @param String $s * * @return Integer */ function firstUniqChar($s) { $map = []; $count = strlen($s); for ($i = 0; $i < $count; $i++) { // 遍历字符串,如果字符串没重复,map中的值将是true if (!isset($map[$s[$i]])) { $map[$s[$i]] = true; continue; }
$map[$s[$i]] = false; }
foreach ($map as $index => $bool) { if ($bool) { // 查询并返回下标 return strpos($s, $index); } }
return -1; }
|