Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
48 lines (44 loc) · 1.32 KB

File metadata and controls

48 lines (44 loc) · 1.32 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.lintcode;
/**
* lintCode 题目113:最长单词
*
* 描述:给一个词典,找出其中所有最长的单词
*
* 样例 {"dog","google","facebook","internationalization","blabla"}
*
* 返回 ["internationalization"]
*
* 挑战:遍历两次的办法很容易想到,如果只遍历一次你有没有什么好办法?
*/
import java.util.List;
import java.util.Stack;
/**
* Created by gegf on 2018/2/6.
*/
public class Solution113 {
/*
* @param dictionary: an array of strings
* @return: an arraylist of strings
*/
public List<String> longestWords(String[] dictionary) {
// write your code here
if(dictionary==null || dictionary.length==0){
return null;
}
Stack<String> maxLenStack = new Stack<String>();
maxLenStack.push(dictionary[0]);
int maxLength = dictionary[0].length();
for (int i = 1; i < dictionary.length; i++) {
if(dictionary[i].length() > maxLength){
maxLength = dictionary[i].length();
maxLenStack.clear();
maxLenStack.push(dictionary[i]);
}else if(dictionary[i].length() == maxLength){
maxLenStack.push(dictionary[i]);
}else{
continue;
}
}
return maxLenStack;
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.