leetcode刷题系列----模式1(Two Points 双指针)- 141:Longest Word in Dictionary through Deleting (Medium) 通过删除字母匹配字典里最长单词
Tips
- 更多题解请见本系列目录
- Java和C#核心代码完全一样, length() and Length, compareTo() and CompareTo(), for and foreach
- 这题比较简单,遍历字符串数组后使用双指针比较目标字符s与字符串数组内的元素。
- 在类内额外定义一个双指针的字符串是否属于子串的函数,代码逻辑结构会更清晰。
Python
class Solution:
def findLongestWord(self, s: str, dictionary: List[str]) -> str:
result = ''
for item in dictionary:
p_item = p_s = 0
while p_item<len(item) and p_s<len(s):
if s[p_s]==item[p_item]:
p_item += 1
p_s += 1
if p_item==len(item):
if len(item)>len(result) or (len(item)==len(result) and result>item):
result = item
return result
C++
class Solution {
public:
string findLongestWord(string s, vector<string>& dictionary) {
string longestWord = "";
for(string target : dictionary)
{
int l1=longestWord.size(), l2=target.size();
if(l1>l2 || (l1==l2 && longestWord.compare(target)<0)) continue;
if(isSubstr(s, target)) longestWord = target;
}
return longestWord;
}
private:
bool isSubstr(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();
}
};
C#
public class Solution {
public string FindLongestWord(string s, IList<string> dictionary) {
string longestWord = "";
foreach(string target in dictionary)
{
int l1=longestWord.Length, l2=target.Length;
if(l1>l2 || (l1==l2 && longestWord.CompareTo(target)<0)) continue;
if(isSubstr(s, target)) longestWord = target;
}
return longestWord;
}
private bool isSubstr(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;
}
}
Java
class Solution {
public String findLongestWord(String s, List<String> d) {
String longestWord = "";
for (String target : d) {
int l1 = longestWord.length(), l2 = target.length();
if (l1 > l2 || (l1 == l2 && longestWord.compareTo(target) < 0)) {
continue;
}
if (isSubstr(s, target)) {
longestWord = target;
}
}
return longestWord;
}
private boolean isSubstr(String s, String target) {
int i = 0, j = 0;
while (i < s.length() && j < target.length()) {
if (s.charAt(i) == target.charAt(j)) {
j++;
}
i++;
}
return j == target.length();
}
}