我写了一个编码挑战。挑战的要求是逆转句子中的特定词,=>仍然保持句子中单词的较多,但使单词的字符发生逆转。
输入示例如下所示:RemoteIo is awesome-Candiates pass interview-best candiates are selected.
上述输入的样本输出:
oIetomeR si emosewa
setaidnaC ssap weivretni
tseb setaidnac era detceles如你所见,输入句子被-字符隔开,这意味着在上面的例子中我们有3个句子,这个句子只包含字母表字符和空格(两个单词之间有一个空格)。
因此,我的问题是如何优化以下代码,并有任何关于代码优化的理论/原则。我的Java代码实现:
public class Test1 {
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
// Put sentences to a String array.
String[] data = input.split("-");
// Loop throw sentence array
for(int i = 0; i < data.length; i++) {
// Put the words from the sentence to a String array.
String[] words = data[i].split(" ");
// Loop throw the word array
for(int w = 0; w < words.length; w++) {
// Revert the characters of each word
for (int j = words[w].length() - 1; j >=0; j--) {
if (j != 0) {
System.out.print(words[w].charAt(j));
} else {
System.out.print(words[w].charAt(j) + " ");
}
}
if ( w == words.length -1) {
System.out.println();
}
}
}
}
}发布于 2022-11-22 17:33:36
下面的代码很糟糕:引用循环变量的ifs令人困惑,从技术上讲,可能比正确的方法慢得多(尽管编译器可能只是为您修复这个问题。) //循环抛出单词数组for(int w= 0;w< words.length;w++) {
// Revert the characters of each word
for (int j = words[w].length() - 1; j >=0; j--) {
if (j != 0) {
System.out.print(words[w].charAt(j));
} else {
System.out.print(words[w].charAt(j) + " ");
}
}
if ( w == words.length -1) {
System.out.println();
}
}相反,请做:
// Loop throw the word array
for(int w = 0; w < words.length; w++) {
// Revert the characters of each word
for (int j = words[w].length() - 1; j >0; j--) {
System.out.print(words[w].charAt(j) + " ");
}
System.out.print(words[w].charAt(j));
}
System.out.println();注意我是如何将j>=0更改为j>0的。else块只会在最后一次重复时触发,因此这在语义上是等价的。
https://stackoverflow.com/questions/74535826
复制相似问题