My code runs find on localhost, why Submission Result: Time Limit Exceeded?


  • 0
    H
    public class Solution {
        public List<List<Integer>> palindromePairs(String[] words) {
        	List<List<Integer>> list = new ArrayList<>();
        	for (int i=0; i<words.length; i++) {
        		for (int j=i; j<words.length; j++) {
        			if (i==j) {
        				continue;
        			}
        			if (isPalindrome(words[i], words[j])) {
        				List<Integer> sublist = new ArrayList<>();
        				sublist.add(new Integer(i));
        				sublist.add(new Integer(j));
        				list.add(sublist);
        			} 
        			if (isPalindrome(words[j], words[i])) {
        				List<Integer> sublist = new ArrayList<>();
        				sublist.add(new Integer(j));
        				sublist.add(new Integer(i));
        				list.add(sublist);
        			}
        		}
        	}
            return list;
        }
        
        public boolean isPalindrome(final String s1, final String s2) {
        	StringBuilder sb = new StringBuilder(s1).append(s2);
        	String ns1 = sb.toString();
        	String ns2 = sb.reverse().toString();
        	return ns1.equals(ns2);
        }
    }

  • 0
    A

    Yes, because your code runs in O(n ^ 2) time. They want a faster algorithm


  • 0

    Because there is no time limit in your localhost, you won't exceed such a thing. But on leetcode, there is.


Log in to reply
 

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