Find the first un-repeated character in a string

后端 未结 30 1402
猫巷女王i
猫巷女王i 2020-11-27 18:29

What is the quickest way to find the first character which only appears once in a string?

30条回答
  •  盖世英雄少女心
    2020-11-27 19:17

    Here's a possible solution in ruby without using Array#detect (as in this answer). Using Array#detect makes it too easy, I think.

    ALPHABET = %w(a b c d e f g h i j k l m n o p q r s t u v w x y z)
    
    def fnr(s)
      unseen_chars    = ALPHABET.dup
      seen_once_chars = []
      s.each_char do |c|
        if unseen_chars.include?(c)
          unseen_chars.delete(c)
          seen_once_chars << c
        elsif seen_once_chars.include?(c)
          seen_once_chars.delete(c)
        end
      end
    
      seen_once_chars.first
    end
    

    Seems to work for some simple examples:

    fnr "abcdabcegghh"
    # => "d"
    
    fnr "abababababababaqababa"                                    
    => "q"
    

    Suggestions and corrections are very much appreciated!

提交回复
热议问题