码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Substring with Concatenation of All Words

时间:2015-02-09 19:49:33      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

 

 

方法一:暴力搜索

针对S中每个字符开始搜索一次长度为wordLen*len的字符串,是否包含L中的所有单词。
这个很好统计,Map就可以直接搞定。思路很好想,同时也很费时。

超时

class Solution {
    map<string, int> m_map;
    public:
        void initMap(vector<string> &L)
        {
            m_map.clear();
            for(size_t i = 0; i <L.size() ; i++)
            {
                if(m_map.find(L[i]) == m_map.end())
                    m_map[L[i]] = 1;
                else
                    m_map [L[i]]++;
            }
        }

        void printMap()
        {
            map<string,int>::iterator it;
            for(it = m_map.begin(); it != m_map.end(); it++)
            {
                cout << it->first << "\t-->\t" << it->second << endl;
            }
            cout << endl;
        }

        vector<int> findSubstring(string S, vector<string> &L)
        {
            vector<int> result;
            if(L.size() == 0)
                return result;

            size_t wordLen = L[0].size();
            size_t wordNum = L.size();
            size_t wordsLen = wordLen * wordNum;

            if(S.size() < wordsLen)
                return result;

            //cout << "wordLen \t" << wordLen << endl;
            //cout << "wordNum \t" << wordNum<< endl;
            //cout << "wordsLen\t" << wordsLen << endl;

            initMap(L);
            //printMap();

            for(size_t i = 0; i <= S.size() - wordsLen; i++)
            {
                size_t j = i;
                for( /**/; j < (i + wordsLen); j += wordLen)
                {
                    //cout << "j\t" << j << endl;
                    //printMap();
                    string tmp = S.substr(j, wordLen);
                    if(m_map.find(tmp) != m_map.end() && m_map[tmp] > 0)
                    {
                        m_map[tmp]--;
                    }
                    else
                    {
                        break;
                    }
                }
                //cout << "==j\t" << j << endl;
                if(j >= (i+wordsLen))
                {
                    result.push_back(i);
                }
                initMap(L);
            }
            return result;

        }
};

 

[LeetCode] Substring with Concatenation of All Words

标签:

原文地址:http://www.cnblogs.com/diegodu/p/4282041.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!