Accepted 94%. Time Limit Exceeded error. What's wrong?


  • 0
    A

    I've got the error of "Time limit exceeded". What's wrong?

    public class Solution {
        public List<Integer> findAnagrams(String s, String p) {
            List<Integer> res = new ArrayList<Integer>();
            if (s.length() < p.length()) return res;
            char[] stdChr = p.toCharArray();
            Arrays.sort(stdChr);
            for (int idx=0; idx<s.length()-p.length()+1; idx++){
                String subStr = s.substring(idx, idx+p.length());
                char[] subChr = subStr.toCharArray();
                Arrays.sort(subChr); 
                if (Arrays.equals(subChr, stdChr)){
                    res.add(idx);
                }
            }
            return res;
        }
    }
    

  • 0

    Time limit exceeded means your code uses too much time
    such as you have used the method String.substring() and Arrays.sort(), they take a lot of overhead
    you can read the source code of the two methods
    Try to improve your algorithm


Log in to reply
 

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