猿问

从字符串中删除字符串重复出现字符中的字符串偶数对字符 - java

我是java初学者,我有这个问题:

**Q01 [ 7 分] 编写一个java 程序,输入字符串,使用EvenPairs(str) 方法检查每个字符(即字母表)是否存在偶数对。示例测试用例

输入:“3gy41d21y363”

输出:

  • 3 – 错误

  • g – 假

  • y – 真

  • 4 – 假

  • 1 – 真

  • d – 假

正如您在输出中看到的,即使重复出现的每个字符也只打印一次,我解决了这个问题,直到这一步我找不到只打印字符 1 次的解决方案,结果是真还是假

这是我的代码:

    package evenpairornot;


import java.util.Scanner;

public class EvenPairOrNot {

static Scanner input = new Scanner(System.in);

public static void main(String[] args) {


    System.out.print("Enter a string: ");

    String s1=input.nextLine();


    EvenPairs(s1);

}


public static void EvenPairs(String s){


    char [] chs=s.toCharArray();

    int count=0;


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

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

            if (chs[i]==chs[j]){

                count++; 

            }    

        } 


        if(count%2==0)

            System.out.println(s.charAt(i)+"- true");

            else

            System.out.println(s.charAt(i)+"- False");


        count=0; 

    }


}

}

这是输出:

输入一个字符串:3gy41d21y363

3- 错误

g- 错误

y-真

4- 错误

1-真

d-错误

2- 错误

1-真

y-真

3- 错误

6- 错误

3- 错误

等待你的帮助!!谢谢你


慕桂英546537
浏览 146回答 1
1回答

慕哥6287543

这是代码。基本上在所有字符数完之后。在打印之前,我向后看以确保它不是重复的。这里有很大的优化空间,比如在计数之前进行检查,或者可以只计算 i 之后的字符而不是计算所有字符。public static void EvenPairs(String s) {&nbsp; &nbsp; char[] chs = s.toCharArray();&nbsp; &nbsp; int count = 0;&nbsp; &nbsp; for (int i = 0; i < chs.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; for (int j = 0; j < chs.length; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (chs[i] == chs[j]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; boolean shouldPrint = true;&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; for (int k = i - 1; k >= 0; k--) {&nbsp; //loop though each character before the current one to check if it was already printed.&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (chs[k] == chs[i]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//if we it was already printed don't print.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; shouldPrint = false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (shouldPrint) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (count % 2 == 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(s.charAt(i) + "- true");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(s.charAt(i) + "- False");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; count = 0;&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答