是否有更好(更有效)的方法来查找字符串是否可以由另一个字符串的字符组成?

时间:2013-08-01 10:12:18

标签: c++ algorithm data-structures map stdmap

这很有趣,因为这是一个可能的面试问题,所以最好知道这个问题最有效的算法。我提出了一个解决方案(其中包含其他人解决方案的元素),需要map<char, int>将第一个字符串中的字母作为键存储,并将其出现的数字作为值存储。然后,算法查看container字符串中的每个字母,并检查地图中是否已有条目。如果是这样,减去它的值直到它为零,依此类推;直到container完成(失败),或直到map为空(成功)。

该算法的复杂性为O(n),O(n)是最坏情况(失败)。

你知道更好的方法吗?

以下是我编写,测试和评论过的代码:

// takes a word we need to find, and the container that might the letters for it
bool stringExists(string word, string container) {

    // success is initially false
    bool success = false;       

    // key = char representing a letter; value = int = number of occurrences within a word
    map<char, int> wordMap;     

    // loop through each letter in the word
    for (unsigned i = 0; i < word.length(); i++) {

        char key = word.at(i); // save this letter as a "key" in a char

        if (wordMap.find(key) == wordMap.end())     // if letter doesn't exist in the map...
            wordMap.insert(make_pair(key, 1));      // add it to the map with initial value of 1

        else
            wordMap.at(key)++;                      // otherwise, increment its value

    }

    for (int i = 0; i < container.size() && !success; i++) {

        char key = container.at(i);

        // if found
        if (wordMap.find(key) != wordMap.end()) {

            if (wordMap.at(key) == 1) { // if this is the last occurrence of this key in map 

                wordMap.erase(key);     // remove this pair

                if (wordMap.empty())    // all the letters were found in the container!
                    success = true;     // this will stop the for loop from running

            }

            else                        // else, if there are more values of this key
                wordMap.at(key)--;      // decrement the count

        }
    }

    return success;
}

1 个答案:

答案 0 :(得分:4)

请勿使用std::map。通常它具有O(log N)写入和O(log N)访问权限。并且malloc调用写。

对于char,您可以使用简单的int freq[256]表(如果您愿意,可以使用std::vector)。

bool stringExists(const string& word, const string& cont) {
  int freq[CHAR_MAX-CHAR_MIN+1]={0};
  for (int c: cont) ++freq[c-CHAR_MIN];
  for (int c: word) if(--freq[c-CHAR_MIN]<0)  return false;
  return true;
}

此代码的复杂性为O(N + M),其中NM为:word.size()cont.size()。而且我猜它即使从小尺寸输入也至少快100倍。