我需要知道字符串中的所有字母是否都是唯一的。要使字符串唯一,字母只能出现一次。如果字符串中的所有字母都是不同的,则该字符串是唯一的。如果多次出现一个字母,则该字符串不是唯一的。
"Cwm fjord veg balks nth pyx quiz."
# => All 26 letters are used only once. This is unique
"This is a string"
# => Not unique, i and s are used more than once
"two"
# => unique, each letter is shown only once
我尝试编写一个函数来确定字符串是否唯一。
def unique_characters(string)
for i in ('a'..'z')
if string.count(i) > 1
puts "This string is unique"
else
puts "This string is not unique"
end
end
unique_characters("String")
我收到了输出
"This string is unique" 26 times.
编辑:
我想谦虚地道歉,因为我的OP中包含了一个不正确的例子。我做了一些研究,试图找到pangrams,并假设它们只包含26个字母。我还要感谢你们指出我的错误。在那之后,我去了维基百科寻找一个完美的pangram(我错误地认为其他人是完美的)。
以下是供参考的链接
http://en.wikipedia.org/wiki/List_of_pangrams#Perfect_pangrams_in_English_.2826_letters.29
再次,我道歉。
答案 0 :(得分:4)
s = "The quick brown fox jumps over the lazy dog."
.downcase
("a".."z").all?{|c| s.count(c) <= 1}
# => false
另一种方法是:
s = "The quick brown fox jumps over the lazy dog."
(s.downcase !~ /([a-z]).*\1/)
# => false
答案 1 :(得分:4)
我会分两步解决这个问题:1)提取字母2)检查是否有重复:
letters = string.scan(/[a-z]/i) # append .downcase to ignore case
letters.length == letters.uniq.length
答案 2 :(得分:2)
这是一个不将字符串转换为数组的方法:
def dupless?(str)
str.downcase.each_char.with_object('') { |c,s|
c =~ /[a-z]/ && s.include?(c) ? (return false) : s << c }
true
end
dupless?("Cwm fjord veg balks nth pyx quiz.") #=> true
dupless?("This is a string.") #=> false
dupless?("two") #=> true
dupless?("Two tubs") #=> false
答案 3 :(得分:0)
def has_uniq_letters?(str)
letters = str.gsub(/[^A-Za-z]/, '').chars
letters == letters.uniq
end
如果这不必区分大小写,
def has_uniq_letters?(str)
letters = str.downcase.gsub(/[^a-z]/, '').chars
letters == letters.uniq
end
答案 4 :(得分:0)
要检查字符串是否唯一,您可以试试这个:
string_input.downcase.gsub(/[^a-z]/, '').split("").sort.join('') == ('a' .. 'z').to_a.join('')
如果字符串中的所有字符都是唯一的,并且它们包含所有26个字符,则返回true。
答案 5 :(得分:0)
如果您想实际跟踪重复的字符:
def is_unique?(string)
# Remove whitespaces
string = string.gsub(/\s+/, "")
# Build a hash counting all occurences of each characters
h = Hash.new { |hash, key| hash[key] = 0 }
string.chars.each { |c| h[c] += 1 }
# An array containing all the repetitions
res = h.keep_if {|k, c| c > 1}.keys
if res.size == 0
puts "All #{string.size} characters are used only once. This is unique"
else
puts "Not unique #{res.join(', ')} are used more than once"
end
end
is_unique?("This is a string") # Not unique i, s are used more than once
is_unique?("two") # All 3 characters are used only once. This is unique
答案 6 :(得分:0)
在您的示例中,您提到您需要有关字符串的其他信息(唯一字符列表等),因此此示例对您也很有用。
# s = "Cwm fjord veg balks nth pyx quiz."
s = "This is a test string."
totals = Hash.new(0)
s.downcase.each_char { |c| totals[c] += 1 if ('a'..'z').cover?(c) }
duplicates, uniques = totals.partition { |k, v| v > 1 }
duplicates, uniques = Hash[duplicates], Hash[uniques]
# duplicates = {"t"=>4, "i"=>3, "s"=>4}
# uniques = {"h"=>1, "a"=>1, "e"=>1, "r"=>1, "n"=>1, "g"=>1}