题目
给出一个字符串数组words组成的一本英语词典。从中找出最长的一个单词,该单词是由words词典中其他单词逐步添加一个字母组成。若其中有多个可行的答案,则返回答案中字典序最小的单词。
若无答案,则返回空字符串。
思路:
暴力解法,先排序,然后从数组倒序进行遍历,看其子串是否在前面出现过
代码:
public String longestWord(String[] words) {
//对原数组中的元素排序
Arrays.sort(words);
String result = "";
int longest = 0;
List<String> ans = new ArrayList<>();
for (int i = words.length - 1; i >= 0; i --) {
String word = words[i];
for (int j = 1; j < word.length();j++) {
String substring = word.substring(0,j);
boolean isContains = Arrays.asList(words).contains(substring);
if (isContains) {
if (j == word.length() -1) {
if (ans.size() == 0) {
ans.add(word);
longest = word.length();
}else {
if (word.length() >= longest) {
ans.add(word);
longest = word.length();
}
}
}
continue;
} else {
break;
}
}
if (word.length() == 1) {
if (ans.size() == 0) {
ans.add(word);
longest = word.length();
}else {
if (word.length() >= longest) {
ans.add(word);
longest = word.length();
}
}
}
}
Arrays.sort(ans.toArray());
if (ans.size() == 0) {
return "";
} else {
return ans.get(ans.size()-1);
}
}```