我参加了一次技术面试,并被问到以下问题:
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/