【问题标题】:How to find duplicated characters如何查找重复的字符
【发布时间】:2021-08-28 12:41:21
【问题描述】:

我的程序返回了错误的答案,即 0,那么我该如何解决呢?它是用 Java 编写的。字符串问题中的重复字符。它必须是“u”和“e”,你能帮我解决这个问题吗?

package sude;

public class deneme {

    public static void main(String[] args) {
        System.out.println(trial("suuudeeeee"));

    }

    public static String trial(String a) {
        for (int i=0; i<=a.length(); i++) {
            for(int j=0;j<=a.length();) {
                if(a.charAt(i)==a.charAt(j)) {
                    return Integer.toString(j);
                }
                else {
                    return "There is no duplicate";
                }
    
            }

        }
        return a;

    }
}

【问题讨论】:

  • 使用调试器逐行逐行执行代码,您会明白为什么它没有按照您的意愿执行。真相就在那里。

标签: java character


【解决方案1】:

首先,您的循环需要删除

第二,你没有迭代'j'。您需要将 j++ 添加到 'j' for 循环中。

第三,如果你的 'i' 和 'j' 都从零开始,所有的字符都会匹配到它们自己。对于每个“i”循环,您都需要在“i”之后开始“j”。

第四,您不能返回单个值并期望两个结果:“u”和“e”。 除非您返回 Collection (或返回 Collection 的字符串值)。

您应该在循环中添加一些打印以调试实际发生的情况。一旦你理解了循环,就可以删除打印输出。

最后一点,为了便于阅读,需要留出一点空白。

public static String trial( String a ) {
    Set<Character> dups = new HashSet<>();

    for ( int i = 0; i < a.length(); i++ ) {
    
        for( int j = i + 1; j < a.length(); j++ ) {

            System.out.println( "i: " + i + " / " + a.charAt( i ) + "; j: " + j + " / " + a.charAt( j ) );

            if( a.charAt( i ) == a.charAt( j ) )
                dups.add( a.charAt( i ) );

        }

    }
    return dups.toString();
}

【讨论】:

    猜你喜欢
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多