要求:
编写程序以接受字符串并以降序打印单词>长度的顺序,不使用数组。
示例:
输入=我爱我的国家印度
输出=国家印度爱我我
我试图通过使用嵌套循环来解决但是更大的输入需要时间。建议一个更好的替代算法...
//Input=I love my country India
//Output=country India love my I
public static void main(String[] JVJplus)
{
String s,temp="",newS="";
int i,j;
System.out.print("Entet s=");
s=in.nextLine()+" ";
for(i=s.length();i>0;i--)
{
for(j=0;j<s.length();j++)
{
char c=s.charAt(j);
if(c!=' ')
temp+=c;
else
{
if(temp.length()==i)
newS+=temp+" ";
temp="";
}
}
}
System.out.println("Output="+newS);
}
答案 0 :(得分:1)
如果您不允许使用数组,那么正则表达式呢?
因此,我们的想法是使用带有临时int变量i
的for循环,该变量使用input
String的长度进行初始化,并且每次迭代减少1。
在循环中,我们正在检查正则表达式,如果input
字符串包含任何长度为i的单词,那就是正则表达式\\b\\w{"+i+"}\\b
匹配的内容:正好连续i
单词字符(=长度= i的任何单词)
最后,如果有匹配,我们将它们打印到sysout。
我们从i = input.length()
开始,因为我们首先想要最长的单词,而整个输入字符串可能是单个单词。
String input = "I love my country India";
for (int i = input.length(); i > 0 ; i--) {
Matcher m = Pattern.compile("\\b\\w{"+i+"}\\b").matcher(input);
while(m.find()){
System.out.print(m.group(0) +" ");
}
}
打印country India love my I
答案 1 :(得分:0)
您可以使用LinkedHashMap(如果单词长度相同,则要根据插入顺序对其进行排序),否则也可以使用HashMap。
我已经使用LinkedHashMap作为解决方案。
Input: "I love my country India"
解决方案:
String sentence = "I love my country India";
StringBuilder sb = new StringBuilder();
LinkedHashMap<String, Integer> hm = new LinkedHashMap<String, Integer>();
for(String word : sentence.split(" ")){
hm.put(word, word.length());
}
hm.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue(Comparator.reverseOrder()))
.forEach(e->{
sb.append(e.getKey() + " ");
});
String result = sb.substring(0).trim();
System.out.print(result);
Output: "country India love my I"
在这种情况下,使用HashMap将提供相同的输出,因为字符串中没有相同长度的单词。