题目描述
给定一个字符串和一个字符串字典,找到字典里面最长的字符串,该字符串可以通过删除给定字符串的某些字符来得到。如果答案不止一个,返回长度最长且字典顺序最小的字符串。如果答案不存在,则返回空字符串。
示例1
输入:s = "abpcplea", d = ["ale","apple","monkey","plea"]输出:"apple"
示例2
输入:s = "abpcplea", d = ["a","b","c"]输出:"a"
解题思路
思路其实很直观,就是遍历字典,然后看在遍历的过程中能否可以通过删除给定字符串的一些字符得到当前遍历的字符,并记录最大值。判断的过程可以采用两个指针,指针i从s开始,指针j从target开始,即对应代码里的func函数
class Solution {public:bool func(string &s, string &target) {int i=0, j=0;while (i<s.length() && j<target.length()) {if (s[i] == target[j])j++;i++;}return j==target.length();}string findLongestWord(string s, vector<string>& d) {string res = "";for (auto tgt : d) {// 因为要求字典序最小,故长度相同且字典序小时直接不需要过func函数if (res.length() > tgt.length() || (res.length() == tgt.length() && res<tgt))continue;if (func(s, tgt))res = tgt;}return res;}};
