Java统计字符串中唯一元音数量:代码无法去重问题求助
Fixing Unique Vowel Counting in Your Code
Got it, let's sort this out! The problem you're hitting is that your current code is likely counting every single vowel occurrence (including repeats) instead of only tracking distinct vowel types. Sets are your best friend here—they automatically handle duplication, so we can use one to keep track of which vowels have appeared at least once.
Step-by-Step Solution
Here's a straightforward implementation (using Python as an example, but the logic translates to most languages):
def count_distinct_vowels(input_str): # Define the set of vowels (adjust case handling as needed) vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} # Initialize an empty set to store unique vowels we find unique_vowels = set() # Iterate through each character in the input string for char in input_str: if char in vowels: unique_vowels.add(char) # The length of the set is the number of distinct vowels return len(unique_vowels)
How It Works
- Set for Vowels: We start with a set of all vowels (both lowercase and uppercase, so we don't miss either).
- Tracking Unique Vowels: As we loop through each character, we add any vowel we find to
unique_vowels—since sets don't allow duplicates, adding the same vowel multiple times does nothing. - Count Distinct Vowels: Finally, the length of
unique_vowelsgives us exactly how many different vowels are present in the string.
Example Usage
If you test this with the string "Hello World!":
print(count_distinct_vowels("Hello World!")) # Output: 2 (e and o)
Optional: Case-Insensitive Counting
If you want to treat 'A' and 'a' as the same vowel, modify the loop to convert each character to lowercase first:
def count_distinct_vowels_case_insensitive(input_str): vowels = {'a', 'e', 'i', 'o', 'u'} unique_vowels = set() for char in input_str.lower(): if char in vowels: unique_vowels.add(char) return len(unique_vowels)
Testing with "Apple":
print(count_distinct_vowels_case_insensitive("Apple")) # Output: 2 (a and e)
内容的提问来源于stack exchange,提问作者Ramsey
相关产品推荐
相关产品推荐

