【发布时间】:2015-04-07 02:56:31
【问题描述】:
我需要从文件中读取内容并找到可以由文件中存在的其他单词组成的最长单词。文件中的单词以空格分隔。例如:
文件输入:
This is example an anexample Thisisanexample Thisistheexample
输出:
Thisisanexample
注意:形成的最长单词是 Thisisanexample 而不是 Thisistheexample,因为单词 the 不包含在文件中作为单独的单词。
这可以通过使用简单的数组来实现吗?我做了以下事情:
try{
File file = new File(args[0]); //command line argument for file path
br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
//array for each word
String[] words = new String[] {};
while ((line = br.readLine()) != null){
words = line.split("\\s+"); //splitting the string with spaces
}
// array to store length of each word
int[] wordLength = new int[words.length];
for(int i = 0; i < words.length; i++){
wordLength[i] = words[i].length();
}
int currLength = 0; //store length of current word
int maxLength = 0; //store length of max word
String maxWord = null;
//checking each word with others at O(n*n) complexity
for (int i = 0; i < words.length; i++){
currLength = 0;
for (int j = 0; j < words.length && j != i; j++){
if (words[i].contains(words[j])){
currLength += wordLength[j];
}
}
System.out.println(currLength);
if(currLength > maxLength){
maxLength = currLength;
maxWord = words[i];
}
}
System.out.println(maxWord);
}
但是如果有一个带有子字符串的子字符串,这将不起作用。它将为以下输入提供错误的输出:
This is example an anexample Thisisanexample Thisisanexample2
输出应该是Thisisanexample,但它给出了Thisisanexample2。
【问题讨论】:
-
纯代码编写请求在 Stack Overflow 上是题外话——我们希望这里的问题与特定编程问题有关——但我们很乐意帮助您自己编写!告诉我们what you've tried,以及您遇到的问题。这也将有助于我们更好地回答您的问题。
-
@huanfeng,和你链接的不一样。
-
@ElliottFrisch ,我已经添加了我写的代码。
-
@titan7585 我明白了,这是一个算法问题,希望有人能帮助你:)