Unable to find what is going on- Pls help


  • 0
    V

    Hi my solution is getting stuck at 34/36 test cases. The error says TLE.
    Please point out what may be causing the problem .

    public class Solution {
        public List<Integer> findAnagrams(String s, String p) {
            int plen = p.length();
            int slen = s.length();
            List<Integer> intList = new ArrayList<Integer>();
            
            if(slen ==0 || plen ==0  || p== null || s== null || slen<plen )
                return intList;
                
            int pos[]= new int[slen];
            //pos stores starting of the occurences of the anagram 
            for(int i=0;i<slen; i++){
                pos[i]=-1;
            }
            
            int count =0;
            char parr[]= p.toCharArray();
            
    // sorting the p string
            for(int i=1;i<plen; i++){
                for(int j=0 ; j<plen-i; j++){
                    if(parr[j]>parr[j+1]){
                        char temp = parr[j];
                        parr[j]= parr[j+1];
                        parr[j+1]= temp;
                        count++;
                    }
                }
                if(count ==0 )
                    break;
            }
            
            String ps = new String(parr);
            
            for(int i=0;i<slen;i++){
                if((i+plen-1)<slen){
                    String now = s.substring(i,i+plen);
                    char nowarr[]= now.toCharArray();
                    int alpha[] = new int[26];
                    
                    for(int j=0 ;j<nowarr.length; j++){
                        alpha[nowarr[j]-97]++;
                    }
                    
                    String nows ="";
                    for(int j=0;j< alpha.length; j++){
                        if(alpha[j]>=1){
                            int co = alpha[j];
                            for(int add=0; add<co; add++)
                                nows += (char)(j+97)+"";
                        }
                    }
                    if(nows.equals(ps)){
                        pos[i]=1;
                    } 
                }
                else 
                    break;
            }
            for (int index = 0; index < slen; index++){
                if(pos[index]==1)
                    intList.add(index);
            }
            return intList;
        }
    }
    
    

Log in to reply
 

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