Word Ladder

来源:互联网 发布:mac appstore 打不开 编辑:程序博客网 时间:2024/06/05 23:16
class Solution {
public:
     bool onediff(string start,string temp)
     {
         int count=0;
         for(int i=0;i<start.size();i++)
         {
             if(start[i]!=temp[i])
              count++;
         }
         return count==1?1:0;
     }
     
    int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {
        
        queue<string>Q1,Q2;
       
        set<string>set1;
       
       int result=1;
        unordered_set<string>::iterator iter;
        Q1.push(beginWord);
        set1.insert(beginWord);
        while(!Q1.empty())
        {
            while(!Q1.empty())
            {
                string temp=Q1.front();
                Q1.pop();
                if(temp==endWord)
                return result++;
            
              for(iter=wordDict.begin();iter!=wordDict.end();iter++)
              {
                  if(onediff(temp,*iter)&&set1.find(*iter) == set1.end())
                 {
                     Q2.push(*iter);
                     
                     set1.insert(*iter);
                 }
                 // if(onediff(*iter,endWord) )   //不能提前跳出,因为同一层后续中可能有endWord;
                //  return result+1; 
                
             }
            }
             result++;
            swap(Q1,Q2);
        }
        return 0;
    }
    

};

超时,当字典中元素较多时不行,不能用onediff函数。

class Solution {
public:
    /* bool onediff(string start,string temp)
     {
         int count=0;
         for(int i=0;i<start.size();i++)
         {
             if(start[i]!=temp[i])
              count++;
         }
         return count==1?1:0;
     }
     */
     
    int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {
        
        queue<string>Q1,Q2;
       
        set<string>set1;
       
       int result=1;
        //unordered_set<string>::iterator iter;
        Q1.push(beginWord);
        set1.insert(beginWord);
        while(!Q1.empty())
        {
            while(!Q1.empty())
            {
                string temp=Q1.front();
                Q1.pop();
               
            
              for(int i=0;i<temp.size();i++)
              {
                  
                 for(char j='a';j<='z';j++)
                 {
                     if(temp[i]==j) continue;
                     swap(temp[i],j);
                    // temp[i] = j;
                      if(temp==endWord)
                   return ++result;
                     if(wordDict.count(temp)!=0&&set1.count(temp)==0)
                    {
                        Q2.push(temp);
                     set1.insert(temp);
                    }
                    swap(temp[i],j);
                    
                 }
                 
                
             }
            }
             result++;
            swap(Q1,Q2);
        }
        return 0;
    }
    
};

0 0
原创粉丝点击