通过删除字母匹配到字典里最长单词
给定一个字符串和一个字符串字典,找到字典里面最长的字符串,该字符串可以通过删除给定字符串的某些字符来得到。如果答案不止一个,返回长度最长且字典顺序最小的字符串。如果答案不存在,则返回空字符串。
示例 1:
输入:
s = “abpcplea”, d = [“ale”,“apple”,“monkey”,“plea”]
输出:
“apple”
示例 2:
输入:
s = “abpcplea”, d = [“a”,“b”,“c”]
输出:
“a”
双指针
先按照字符串长度和字典序排序
分别用first指针指向s的头 second指针指向字典中某个字符串的头。
如果s[first]==d[i][second],则first=++;second++;如果不等,那就first++,当退出循环时,即second在first走过s末尾前先走到d[i]末尾(字典中这个字符串的字母按照顺序都出现在s中了),找出的第一个则是符合要求的且最长字典序最小的字典中字符串,返回即可。
题解代码
class Solution {
public:
bool checkSub(string& src, string& dst)
{
int i = 0;
int j = 0;
for (; i < src.size() && j < dst.size(); i++) {
if (src[i] == dst[j]) {
j++;
}
}
return j == dst.size();
}
string findLongestWord(string s, vector<string>& dictionary) {
auto cmp = [&] (string& a, string& b) {
if (a.size() == b.size()) {
return a < b;
}
return a.size() > b.size();
};
sort(dictionary.begin(), dictionary.end(), cmp);
for (int i = 0; i < dictionary.size(); i++) {
if (checkSub(s, dictionary[i])) {
return dictionary[i];
}
}
return "";
}
};
我的代码
class Solution {
public:
string findLongestWord(string s, vector<string>& dictionary) {
int first,second;
int m=dictionary.size();
int flag[m];int max=0,re=-1;int F=0;vector<int>same;int temp;
for(int i=0;i<m;i++)
{
first=0;second=0;
while(first<s.size()&&second<dictionary[i].size())
{
if(s[first]==dictionary[i][second])
{
first++;second++;
}
else
{
first++;
}
}
if(second==dictionary[i].size())
{
flag[i]=1;
}
else{
flag[i]=0;
}
}
for(int i=0;i<m;i++)
{
if(flag[i]==1&&dictionary[i].size()>max)
{
max=dictionary[i].size();
}
}
for(int i=0;i<m;i++)
{
if(flag[i]==1&&dictionary[i].size()==max)
{
same.push_back(i);
}
}
if(same.size()==1)
{
re=same[0];
}
else if(same.size()>0)
{
re=0;
for(int i=0;i<same.size();i++)
{
if(dictionary[re].compare(dictionary[i])>0)
{
re=i;
}
}
}
if(re!=-1)
{
return dictionary[re];
}
else{
return "";
}
}
};
我绝大部分样例能过 提交时有个巨长的样例过不去没看出为什么T.T
本文介绍了一种算法,用于从字典中寻找可通过删除给定字符串某些字符得到的最长单词,并提供两种实现方式,包括双指针法及排序与比较法。
566

被折叠的 条评论
为什么被折叠?



