Concise java < 800ms solution


  • 0
    A

    Any feedback?
    """

    public boolean isAnagram(String s, String p) {
    	int[] counts = new int[26];
    	for (int i = 0; i < s.length(); i++) {
    		counts[s.charAt(i) - 'a']++;
    		counts[p.charAt(i) - 'a']--;
    	}
    	for (int i : counts) {
    		if (i != 0)
    			return false;
    	}
    	return true;
    
    }
    public List<Integer> findAnagrams(String s, String p) {
    	List<Integer> result = new ArrayList<Integer>();
    	if (s == null || s.length() == 0 || p == null || p.length() == 0) {
    		return result;
    	}
    	if (s.length() < p.length()) {
    		return result;
    	}
    	int pLen = p.length();
    	for (int i = 0; i < s.length() - pLen + 1; i++) {
    		if (isAnagram(s.substring(i, i + pLen), p)) {
    			result.add(i);
    		}
    	}
    	return result;
    }
    

    """


  • 0
    J

    The C++ implementation seems to cause TLE

    class Solution {
    private:
        bool isAnagram(string s, string p) {
            vector<char> letter(26, 0);
            int size = s.size();
            for (int i = 0; i < size; i++) {
                letter[s[i]-'a']++;
                letter[p[i]-'a']--;
            }
            for (int i = 0; i < 26; i++)
                if (letter[i] != 0)
                    return false;
            return true;
        }
    public:
        vector<int> findAnagrams(string s, string p) {
           int j = s.size() - p.size();
           
           vector<int> r;
           if (j < 0) return r;
           
           int size = p.size();
           for (int i = 0; i <= j; i++) {
               if (isAnagram(s.substr(i, size), p))
                 r.push_back(i);
           }
           return r;
        }```
    };

Log in to reply
 

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