C++ 穷举搜索


  • 0
    J
    
    class Solution {
    public:
        string replaceWords(vector<string>& dict, string sentence) {
            string result;
            string token;
            stringstream ss(sentence); // Insert the string into a stream
            while(ss>>token)
            {
                string replace = find_root(dict,token);
                result  = result + replace;
                result+=" ";
            }
            return result.substr(0,result.size()-1);  
        }
    private:
        string find_root(vector<string>& dict,string token)
        {
            string result = token;
            for(int i = 0;i<dict.size();i++)
            {
                if(isPrefix(dict[i],token) && dict[i].size()<result.size()) 
                        result = dict[i];
            }
            return result;
        }
        
        bool isPrefix(string source, string target)
        {
            return target.find(source)==0?true:false;
        }
    
    };
    

Log in to reply
 

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