JAVA-Time limit exceeded


  • 0
    B
    public class Solution {
    public String reverseWords(String s) {
        String reverse = "";
        String[] tokens = s.split(" ");
        for(int i = tokens.length - 1; i >= 0; i--){
            reverse = reverse + tokens[i];
            if (i != 0){
                reverse +=" ";
            }
        }
        return reverse;
    }
    

    }

    I got an Time Limit Exceeded error...


  • 2
    V

    Use StringBuilder instead.
    a String is immutable, so if there are 10^5 tokens, your program generates 10^5 different strings.


  • 0
    W

    Yes! I use SB, and passed


Log in to reply
 

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