无法定位运行时错误根源:HackerRank Minion Game代码求助
Hey there! Let's break down why your code might be hitting errors (like timeouts or memory limits) on HackerRank's Minion Game problem.
The Core Problem with Your Current Code
Your approach stores every single valid substring in lists st and ke before counting their lengths. For a string of length n, this creates O(n²) substrings—way too many when n is large (like HackerRank's test cases that might use strings with thousands of characters).
For example, if the input string is 1000 characters long, your code would generate 500,500 substrings. That's a massive amount of memory usage, and the nested loops will take way too long to run, leading to timeouts or memory errors.
A Better Approach: Calculate Scores Directly
You don't need to store any substrings at all! Instead, calculate the score for each player on the fly:
- Stuart's score: Sum the number of substrings starting with each consonant. For a character at index
i, there arelen(s) - isubstrings starting ati(since you can take the substring fromitoi,itoi+1, ...,ito the end of the string). - Kevin's score: Do the same for vowels (A, E, I, O, U).
Fixed Code
def minion_game(s): vowels = {'A', 'E', 'I', 'O', 'U'} stuart_score = 0 kevin_score = 0 n = len(s) for i in range(n): if s[i] in vowels: kevin_score += n - i else: stuart_score += n - i if stuart_score > kevin_score: print(f"Stuart {stuart_score}") elif kevin_score > stuart_score: print(f"Kevin {kevin_score}") else: print("Draw") if __name__ == '__main__': s = input().strip() minion_game(s)
Why This Works
- Memory Efficiency: We only use a few variables to track scores, no huge lists of substrings.
- Time Efficiency: Runs in O(n) time (single loop through the string), which handles even the largest input sizes easily.
内容的提问来源于stack exchange,提问作者user350331

