Why my Java Solution Exceed Time limit?


  • 0
    Q

    {

      public int ladderLength(String start, String end, Set<String> dict) {
        	HashMap<String,Boolean> myHash=new HashMap<String,Boolean>();
        	Set<Entry<String,Boolean>> set=myHash.entrySet();
        	for(String string:dict){
        		myHash.put(string, false);
        	}
            
            Queue<MyNode> queue=new ArrayDeque<MyNode>();
            
            queue.add(new MyNode(1,start));
            
            while(!queue.isEmpty()){
            	
            	MyNode node=queue.remove();
            	
            	if(checkDistance(node.word,end)){
            		return node.distance+1;
            	}
            	else{
            	//	Set<Entry<String,Boolean>> set=myHash.entrySet();
            		for(Entry<String,Boolean> s : set){
            			if(!s.getValue()&&checkDistance(s.getKey(),node.word)){
            				queue.add(new MyNode(node.distance+1,s.getKey()));
            				myHash.put(s.getKey(), true);
            			}
            			else{
            				continue;
            			}
            		}
            	}
            }
            
            return 0;
            
            
        }
    
        public boolean checkDistance(String a,String b){
        	int count=0;
        	for(int i=0;i<a.length();i++){
        		String compareA=a.substring(i, i+1);
        		String compareB=b.substring(i, i+1);
        		if(!compareA.equals(compareB)){
        			count++;
        		}
        		if(count>=2){
        			return false;
        		}
        	}
        	return true;
        }
    
        class MyNode{
        	public int distance;
        	public String word;
        	public MyNode(int distance, String word){
        		this.distance=distance;
        		this.word=word;
        	}
        }
    

    }

    }


Log in to reply
 

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