Leetcode first click _ Word Break

Source: Internet
Author: User

At first glance, we will immediately think of recursion, but the cost of direct recursion is too high. When the word length in the dictionary is very small and the word length is very long, it will definitely time out. Let's take a closer look. Is it necessary to perform recursive verification every time? If it is not verified from position I, other recursive branches do not need to go when they reach this position, because it must be a dead end. When I think of creating a table, I can record the locations that cannot be used, which significantly improves the speed.

The following is a bit of implementation. It is impossible to record a location. map is the simplest and most direct, and the search speed is fast. Each time you select the step size, you do not need to go from 0 to length. My approach is to first count the longest and smallest word lengths, and each time you verify this length, you can.

The code is very simple and generally does not cause errors:

int mmin = 0x7fffffff, mmax = 0;map<int, bool> visited;bool pwordBreak(string &s, int start, unordered_set<string> &dict){    if(start >= s.length())        return true;    if(visited.find(start) != visited.end())        return visited[start];    for(int i=mmin;i<=mmax&&start+i<=s.length();i++){        string sb = s.substr(start, i);        if(dict.find(sb) != dict.end()){            if(pwordBreak(s, start+i, dict)){                visited[start+i] = true;                return true;            }else{                visited[start+i] = false;            }        }    }    return false;}class Solution {public:    bool wordBreak(string s, unordered_set<string> &dict) {        unordered_set<string>::const_iterator it = dict.begin();        while(it != dict.end()){            mmin = min(mmin, (int)(*it).length());            mmax = max(mmax, (int)(*it).length());            it++;        }        visited.clear();        return pwordBreak(s, 0, dict);    }};


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.