题目描述:
720. 词典中最长的单词 - 力扣(LeetCode) (leetcode-cn.com)
自测用例:
["w","wo","wor","worl","world"]
["a","banana","app","appl","ap","apply","apple"]
["ab","abc"]
["a"]
["a","b"]
["b","a"]
["a","b","bc"]
["ab"]
["rac","rs","ra","on","r","otif","o","onpdu","rsf","rs","ot","oti","racy","onpd"]
Java代码:
class Solution { public String longestWord(String[] a) { Arrays.sort(a); String ans=""; HashSet<String> set=new HashSet<>(); for(String s:a){ if(s.length()==1||set.contains(s.substring(0,s.length()-1))){ if(ans.length()<s.length())ans=s; set.add(s); } } return ans; } }