声明:原题目转载自LeetCode,解答部分为原创
Problem :
Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
Example 1:
Input: s = "abpcplea", d = ["ale","apple","monkey","plea"] Output: "apple"
Example 2:
Input: s = "abpcplea", d = ["a","b","c"] Output: "a"
Solution:
思路:先将vector容器中“能够通过删减给定字符串s的某些字母而得到的字符串”存到sub_set容器中,再对sub_set容器存放的字符串进行排序,然后输出头元素。根据题意,需要重新定义cmp()比较函数,当字符串a、b满足a.size() = b.size()时,将字典序小的放在前;否则,将size()大的字符串放在前。
代码如下:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool cmp(string a, string b)
{
if(a.size() == b.size())
return a < b;
else if(a.size() > b.size())
return true;
else
return false;
}
class Solution {
public:
string findLongestWord(string s, vector<string>& d) {
vector<string> sub_set;
for(int i = 0 ; i < d.size() ; i ++)
{
if(valid_s(s, d[i]))
sub_set.push_back(d[i]);
}
if(!sub_set.empty())
{
sort(sub_set.begin(), sub_set.end(), cmp);
return sub_set.front();
}
else
return "";
}
private:
bool valid_s(string sub, string d) {
int point_0 = 0;
int point_1 = 0;
while(point_1 < d.size() && point_0 < sub.size())
{
if(d[point_1] == sub[point_0])
{
point_0 ++;
point_1 ++;
}
else
{
point_0 ++;
}
}
if(point_1 == d.size())
return true;
else
return false;
}
};
int main()
{
vector<string> text_1;
vector<string> text_2;
text_1.push_back("abpcplea");
text_2.push_back("plea");
text_2.push_back("ale");
text_2.push_back("apple");
text_2.push_back("monkey");
Solution text;
cout << text.findLongestWord(text_1.front(), text_2) << endl;
return 0;
}