数组中两个字符串的最小距离
题目
给定一个字符串数组strs,再给定两个字符串str1和str2,返回在strs中str1和str2的最小距离,如果str1和str2为NULL,或不在strs中,返回-1。
进阶题目:如果查询发生的次数较多,如何把每次查询的时间复杂度将为O(1)?
代码
原问题使用map进行记录依次更新即可,进阶问题在书中的方法是使用了一个map<string, map<string, int>>进行记录。具体分析参考书籍
#include<iostream>
#include<string>
#include<algorithm>
#include<map>
using namespace std;
int minDistance(string strs, string s1, string s2)
{
if (s1.size() < 1 || s2.size() < 1)
return -1;
if (s1 == s2)
return 0;
int last1 = -1;
int last2 = -1;
int len = strs.size();
int MIN = INT_MAX;
for (int i = 0; i < len; i++)
{
if (strs[i] == *s1.c_str())
{
MIN = min(MIN, last2 == -1 ? MIN : i - last2);
last1 = i;
}
if (strs[i] == *s2.c_str())
{
MIN = min(MIN, last1 == -1 ? MIN : i - last1);
last2 = i;
}
}
return MIN == INT_MAX ? -1 : MIN;
}
class record
{
private:
map<string, map<string, int>> recordD;
void update(map<string, int> &indexMap, string str, int i);
public:
record(string str);
int minDistance(string str1, string str2);
};
record::record(string str)
{
map<string, int> indexMap;
for (int i = 0; i != str.size(); i++)
{
string curStr = str.substr(i, 1);
update(indexMap, curStr, i);
indexMap[curStr] = i;
}
}
void record::update(map<string, int> &indexMap, string str, int i)
{
if (indexMap.find(str) == indexMap.end())
{
map<string, int> newSubMap;
recordD.insert(pair<string, map<string, int>>(str, newSubMap));
}
map<string, int>strMap = recordD[str];
//map<string, int>::iterator my_it = strMap.begin();
for (pair<string, int> m: strMap)
{
string key = m.first;
int index = m.second;
if (key != str)
{
map<string, int> lastMap = recordD[key];
int curMin = i - index;
if (strMap.find(key) != strMap.end())
{
int preMin = strMap[key];
if (curMin < preMin)
{
strMap[key]