String - find maximum occurring character in string Given a string S, find the maximum occurring character in the input string. e.g., if the input string is “test” then the function should return ‘t’. Input: hello world where: First-line represents the input string Output: l Explanation: As the letter l occurs the most number of times in the input string S. Assumptions: The length of the string S can be 0 to 10000. Input string S contains only lower case characters.
时间: 2024-01-08 12:02:37 浏览: 102
MODE_Switch2.rar_The Just_event triggered
To find the maximum occurring character in a given string, we can use a dictionary to keep track of the frequency of each character. We can iterate through the string, and for each character, we can update the frequency count in the dictionary. Finally, we can find the character with the highest frequency in the dictionary.
Here's the Python code to implement this:
```
def max_occuring_char(s):
freq = {}
for char in s:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
max_char = ''
max_freq = 0
for char in freq:
if freq[char] > max_freq:
max_char = char
max_freq = freq[char]
return max_char
# test the function
s = 'hello world'
print(max_occuring_char(s)) # output: l
```
In this code, we first initialize an empty dictionary `freq` to store the frequency counts of each character. Then, we iterate through the input string `s` and update the frequency count for each character in the dictionary.
Next, we iterate through the dictionary to find the character with the highest frequency count. We initialize `max_char` and `max_freq` variables to keep track of the character with the highest frequency and its frequency count. We compare the frequency count of each character in the dictionary with the current maximum frequency count, and update `max_char` and `max_freq` accordingly.
Finally, we return the character with the highest frequency count.
阅读全文