3 回答
TA贡献1802条经验 获得超4个赞
首先,您可以使用此处建议的内容从字符串中删除重复的数字:
然后,您可以在每次找到匹配项时使用 break 语句离开内部循环:
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));
break;
}
}
}
}
TA贡献1773条经验 获得超3个赞
如果您不想重复,请使用Set.
这也将执行更好的O(n+m),而不是代码的O(n*m)。
static void commun(String tel1, String tel2) {
Set<Integer> chars1 = tel1.chars().boxed().collect(Collectors.toSet());
Set<Integer> chars2 = tel2.chars().boxed().collect(Collectors.toSet());
chars1.retainAll(chars2);
for (int ch : chars1)
System.out.printf(" %c,", (char) ch);
}
测试
commun("5143436111", "4501897654");
输出
1, 4, 5, 6,
TA贡献2016条经验 获得超9个赞
试试这个:
public class numerodetel {**strong text**
static void commun(String tel1, String tel2){
dstr="";
for(int i=0;i<tel1.length();i++){
if (dstr.indexOf(tel1.charAt(i)) >= 0)
continue;
for(int j=0;j<tel2.length();j++){
if (tel1.charAt(i)==tel2.charAt(j)) {
dstr += tel1.charAt(i);
System.out.printf(" %c,", tel1.charAt(i));
}
}
}
}
public static void main(String[] args){
String telUDM = "5143436111", telJean = "4501897654";
commun(telUDM, telJean);
}
}
只需更新您自己的代码。
在这里维护一个dumplicates字符串dstr,常用字符将添加到其中。
当其中已经有一个字母时,将跳过比较continue。
indexOf将返回字母在字符串中的位置,或者-1如果不在其中。
添加回答
举报
