Dear friends and community,how to deal with TLE in Python,thank you


  • 0
    R

    Dear friens and community,
    I try to solve this problem in Python as follows:

    class Solution(object):
        def reverseString(self, s):
            """
            :type s: str
            :rtype: str
            """
            res=""
            for i in range(len(s)):
                res+=s[len(s)-i-1]
            return res
    

    The Time Limit Exceeded(TLE) is produced,however,if my code is as follows:

    return s[::-1]
    

    It's accepted.
    And how to deal with the TLE in the first type code in Python,3q very much


  • 0
    S

    String object is immutable in Python, so it creates a new object and assign it to res when using "+=".
    It's too inefficient for long input string, so there occurs the TLE.
    Use join() instead?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.