java - 解决方案评论 : reversing words in a sentence

标签 java algorithm

我参加了一次技术面试,并被问到以下问题:

Write a function that takes a sentence and returns the sentence with the words in reverse order (i.e. "hello world" becomes "world hello").

这是我用 Java 给出的解决方案:

/** Takes a sentence as an input and returns the sentence with the words in
 *  reversed order. */
private static String reverseSentence(String sentence) {
    String[] words = sentence.split("\\s+");
    String reversedString = "";
    for (int k = words.length - 1; k >= 0; k -= 1) {
        reversedString += " " + words[k];
    }
    return reversedString.substring(1);
}

我开始思考必须有比这更有效的方法来解决这个问题。如果这个解决方案被证明是最好的并且没有比这更高效/优雅的解决方案,我不会在顶级公司的技术面试中看到这个问题。

谁能想到更好的方法来做到这一点?

最佳答案

以下是连接句子元素的更好方法:What's the most elegant way to concatenate a list of values with delimiter in Java?

此外,sentence.split("\\s+") 仅在输入干净时才有效(人们确实会打错字)。还有问题应该如何处理标点符号。 世界!你好, 确实看起来很奇怪。

关于java - 解决方案评论 : reversing words in a sentence,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27101938/

相关文章:

c# - 比较网站的文本内容

java - 如何从 JavaFx 中的任务发送 int?

algorithm - 如何在这些约束条件下优化分配给代理的任务?

java - 使用 JButton 在运行时添加新面板

java - 是否必须在 Activity 中编写 Alert Dialog 打开代码?

c - 按特定顺序对三个数字进行排序

algorithm - CUDA 中 Smith-Waterman 算法的矩阵填充

php str_replace 是用什么字符串匹配算法写的?

java - 替换从 javascript 获取的字符

java - 什么是更好的 Java Web 应用程序框架(请提出建议)?