有用的for循环(524. Longest Word in Dictionary through Deleting)

来源:互联网 发布:sql中join的用法例子 编辑:程序博客网 时间:2024/06/14 00:48

有一个实际的问题:给定两个字符串,怎么去判断一个字符串中的字母在另一个中都能被匹配?比如abcppdlfe和apple,我们能够看出来apple能够在abcppdlfe中得到匹配。

这里会用到一种典型的找相同的方法,类似于以前遇到的“双指针”,这里需要同向扫描过来:

for(int i=0,j=0;i<s1.size()&&j<s2.size();i++)    j+=(s1[i]==s2[j]);
画一张图就能看懂这段代码的作用了:从s1的第0个字符开始,和s2作比较,s2的下标始终停在那里,除非能在s1中找到相同的。这是一个很有用的for循环。

LeetCode上的题:

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"

Note:

  1. All the strings in the input will only contain lower-case letters.
  2. The size of the dictionary won't exceed 1,000.
  3. The length of all the strings in the input won't exceed 1,000.
AC代码:
class Solution {public:    string findLongestWord(string s, vector<string>& d) {        string res;        for(int i=0;i<d.size();i++){            int pi=0,pj=0;            for(;pi<s.size()&&pj<d[i].size();pi++)                pj+=(s[pi]==d[i][pj]);            if(pj==d[i].size()&&(res.size()<d[i].size()||(res.size()==d[i].size()&&res>d[i])))                res=d[i];        }        return res;    }};




阅读全文
0 0
原创粉丝点击