缩小字符串之间的共同元素

public class numerodetel {**strong text**    

static void commun(String tel1, String tel2){

    for(int i=0;i<tel1.length();i++){

        for(int j=0;j<tel2.length();j++){

            if(tel1.charAt(i)==tel2.charAt(j))

                System.out.printf(" %c,", tel1.charAt(i));


        }


    }

}

public static void main(String[] args){

        String telUDM = "5143436111", telJean = "4501897654";


        commun(telUDM, telJean);

    }

}

该代码有效,我能够找到两个电话号码之间的公共号码。但是,有没有一种简单的方法可以使它一旦在两者之间检测到一个共同的数字,它就不会再次出现?在这种情况下,它将是 5、1、4、6。


www说
浏览 176回答 3
3回答

慕虎7371278

首先,您可以使用此处建议的内容从字符串中删除重复的数字:然后,您可以在每次找到匹配项时使用 break 语句离开内部循环:static void commun(String tel1, String tel2) {&nbsp; &nbsp; for(int i=0;i<tel1.length();i++) {&nbsp; &nbsp; &nbsp; &nbsp; for(int j=0;j<tel2.length();j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(tel1.charAt(i)==tel2.charAt(j)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.printf(" %c,", tel1.charAt(i));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

慕容3067478

如果您不想重复,请使用Set.这也将执行更好的O(n+m),而不是代码的O(n*m)。static void commun(String tel1, String tel2) {&nbsp; &nbsp; Set<Integer> chars1 = tel1.chars().boxed().collect(Collectors.toSet());&nbsp; &nbsp; Set<Integer> chars2 = tel2.chars().boxed().collect(Collectors.toSet());&nbsp; &nbsp; chars1.retainAll(chars2);&nbsp; &nbsp; for (int ch : chars1)&nbsp; &nbsp; &nbsp; &nbsp; System.out.printf(" %c,", (char) ch);}测试commun("5143436111", "4501897654");输出&nbsp;1, 4, 5, 6,

慕沐林林

试试这个:public class numerodetel {**strong text**&nbsp; &nbsp;&nbsp;static void commun(String tel1, String tel2){&nbsp; &nbsp; dstr="";&nbsp; &nbsp; for(int i=0;i<tel1.length();i++){&nbsp; &nbsp; &nbsp; &nbsp; if (dstr.indexOf(tel1.charAt(i)) >= 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; for(int j=0;j<tel2.length();j++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (tel1.charAt(i)==tel2.charAt(j)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dstr += tel1.charAt(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.printf(" %c,", tel1.charAt(i));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}public static void main(String[] args){&nbsp; &nbsp; &nbsp; &nbsp; String telUDM = "5143436111", telJean = "4501897654";&nbsp; &nbsp; &nbsp; &nbsp; commun(telUDM, telJean);&nbsp; &nbsp; }}只需更新您自己的代码。在这里维护一个dumplicates字符串dstr,常用字符将添加到其中。当其中已经有一个字母时,将跳过比较continue。indexOf将返回字母在字符串中的位置,或者-1如果不在其中。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java