首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何优化代码和代码优化理论

如何优化代码和代码优化理论
EN

Stack Overflow用户
提问于 2022-11-22 16:17:12
回答 1查看 49关注 0票数 0

我写了一个编码挑战。挑战的要求是逆转句子中的特定词,=>仍然保持句子中单词的较多,但使单词的字符发生逆转。

输入示例如下所示:RemoteIo is awesome-Candiates pass interview-best candiates are selected.

上述输入的样本输出:

代码语言:javascript
复制
oIetomeR si emosewa 
setaidnaC ssap weivretni 
tseb setaidnac era detceles

如你所见,输入句子被-字符隔开,这意味着在上面的例子中我们有3个句子,这个句子只包含字母表字符和空格(两个单词之间有一个空格)。

因此,我的问题是如何优化以下代码,并有任何关于代码优化的理论/原则。我的Java代码实现:

代码语言:javascript
复制
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();
                }
            }
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2022-11-22 17:33:36

下面的代码很糟糕:引用循环变量的ifs令人困惑,从技术上讲,可能比正确的方法慢得多(尽管编译器可能只是为您修复这个问题。) //循环抛出单词数组for(int w= 0;w< words.length;w++) {

代码语言:javascript
复制
                // 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();
                }
            }

相反,请做:

代码语言:javascript
复制
  // 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块只会在最后一次重复时触发,因此这在语义上是等价的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74535826

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档