想法:
朋友们,&&和||的运算优先级是不一样的!!
||的优先级比&&低!看我打星号的语句,就是这里出了问题=-=
讲点别的,这道题,我看到字典就以为是我没学过的数据结构,看了答案才发现我的思路大致是对的,然后就写出来了。
题目:
给你一个字符串 s 和一个字符串数组 dictionary 作为字典,找出并返回字典中最长的字符串,该字符串可以通过删除 s 中的某些字符得到。
如果答案不止一个,返回长度最长且字典序最小的字符串。如果答案不存在,则返回空字符串。
示例 1:
输入:s = "abpcplea", dictionary = ["ale","apple","monkey","plea"]
输出:"apple"
示例 2:
输入:s = "abpcplea", dictionary = ["a","b","c"]
输出:"a"
提示:
1 <= s.length <= 1000
1 <= dictionary.length <= 1000
1 <= dictionary[i].length <= 1000
s 和 dictionary[i] 仅由小写英文字母组成
AC代码:
class Solution {
public:
bool is_in(string s,string s1){
int i = 0,j = 0;
while(i < s.length() && j < s1.length()){
if(s[i] == s1[j]){
i++;
j++;
}
else{
i++;
}
}
if(j == s1.length()) return true;
else return false;
}
string findLongestWord(string s, vector<string>& dictionary) {
unsigned int i;
unsigned int longest = 0;
unsigned int len = 0;
string longest_s = "";
for(i = 0;i < dictionary.size();i++)
{
if((dictionary[i].length() > len || (dictionary[i].length() == len && dictionary[i] < longest_s)) && is_in(s,dictionary[i]))//这是一条打星号的语句
{
longest = i;
len = dictionary[i].length();
longest_s = dictionary[i];
}
}
return longest_s;
}
};