简单字符串处理:Leetcode 599:两个列表的最小索引总和
问题:
思路:
使用STL中的无序关联容器unordered_map,键为字符串,对应的值为索引。将list1中的数据加入容器中,设索引和最小值的初始值为10000,对于list2中的字符串,查找容器中是否有键值相等的元素(相等的字符串),若有,计算索引和,若小于当前最小值,将最小值更新,并将已保存的全部字符串清除(找到了更好的最小索引)。若索引和与当前最小值相同,则将当前字符串保存。
代码:
class Solution {
public:
vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
unordered_map<string,int> table;
vector<string> ans;
int i;
for( i=0;i<list1.size();i++ )
{
table[ list1[i] ]=i;
}
int max=10000;
for( i=0;i<list2.size();i++ )
{
if( table.count( list2[i] )!=0 )
{
if( table[ list2[i] ]+i<max )
{
max=i+table[ list2[i] ];
ans.erase( ans.begin(),ans.end() );
ans.push_back( list2[i] );
}
else if( table[ list2[i] ]+i==max )
ans.push_back( list2[i] );
}
}
return ans;
}
};