Please Help Getting TLE C++


  • 0
    N

    please help do not understand why im getting a TLE

    class Solution {
    public:
        int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
           queue<pair<string,int>> q;
           q.push(make_pair(beginWord, 0));
           wordList.insert(endWord);
           while(!q.empty() && !wordList.empty())
           {
               auto node = q.front();
               if(node.first == endWord)
                return node.second;
               for(int i=0; i<node.first.length(); i++)
               {
                   string s = node.first;
                   char letter = s[i];
                   for(char c='a'; c<='z'; c++)
                   {
                       if(c == letter)
                        continue;
                       if(wordList.count(s))
                       {
                           if(s == endWord)
                           {
                                return node.second+1;
                           }
                            else
                            {
                               q.push(make_pair(s,node.second+1));
                               wordList.erase(wordList.find(s));
                            }
                       }
                   }
                   s[i] = letter;
               }
           }
           return 0;
        }
    };
    </pre>

Log in to reply
 

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