- 更多题解请见本系列目录
- Java和C#核心代码完全一样, length() and Length, compareTo() and CompareTo(), for and foreach
- 这题比较简单,遍历字符串数组后使用双指针比较目标字符s与字符串数组内的元素。
- 在类内额外定义一个双指针的字符串是否属于子串的函数,代码逻辑结构会更清晰。
class Solution: def findLongestWord(self, s: str, dictionary: List[str]) -> str: result = '' for item in dictionary: p_item = p_s = 0 while p_itemC++len(result) or (len(item)==len(result) and result>item): result = item return result
class Solution { public: string findLongestWord(string s, vectorC#& 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(); } };
public class Solution { public string FindLongestWord(string s, IListJavadictionary) { 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; } }
class Solution { public String findLongestWord(String s, Listd) { 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(); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)