C/C++教程

#力扣LeetCode720. 词典中最长的单词 @FDDLC

本文主要是介绍#力扣LeetCode720. 词典中最长的单词 @FDDLC,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

题目描述:

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;
    }
}

这篇关于#力扣LeetCode720. 词典中最长的单词 @FDDLC的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!