如何找到一个给定的字符串中的第一个字符,即只出现一次第一个、字符串、字符

2023-09-11 06:12:43 作者:她的轮廓

这是一个面试问题。找到一个给定的字符串,即只出现一次的第一个字符(我猜想的解决方案应该是在Java中)。

This is an interview question. Find the first character in a given string, that appears only once (I suppose the solution should be in Java).

例如:


"babcbcd" -> 'a' // both 'a' and 'd' appear only once but 'a' appears before 'd'

在平凡的解决方案是

The trivial solution is

打造的地图的(例如:的HashMap ):字符 - >其字符串中的出现次数; 扫描字符串,字符串测试对人物的地图的字符,直到值的值为1。 build a map (e.g. HashMap): char -> number of its appearances in the string; scan the string and test string characters against the map until the value of the character is 1.

是否有意义?什么是最好的地图的实施?有没有更好的,更有效的解决方案?

Does it make sense? What is the best map implementation? Is there any better, more efficient solution?

推荐答案

下面是一个版本哈斯克尔。

Here's a version in Haskell.

import Data.List (elemIndices)
firstSingle str = take 1 [a | a <- str, length (elemIndices a str) == 1]

*主要Data.List模块> firstSinglebabcbcd 一个

*Main Data.List> firstSingle "babcbcd" "a"