首页 > 解决方案 > 删除字符串中的偶数对字符从字符串中重复出现字符 - java

问题描述

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

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

输入:“3gy41d21y363”

输出:

正如您在输出中看到的那样,即使重复出现每个字符也只打印一次,直到这一步我才解决了问题

这是我的代码:

    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-错误

是的

4-错误

1-真

d- 错误的

2-错误

1-真

是的

3-错误

6-错误

3-错误

等待你的帮助!!谢谢你

标签: java

解决方案


这是代码。基本上所有字符都算完之后。我向后看,以确保在打印之前它不是重复的。这里有很大的优化空间,比如在计数之前进行检查,或者不计算所有字符,您可以只计算 i 之后的字符。

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++;
            }
        }

        boolean shouldPrint = true;  
        for (int k = i - 1; k >= 0; k--) {  //loop though each character before the current one to check if it was already printed. 
            if (chs[k] == chs[i]) {         //if we it was already printed don't print.
                shouldPrint = false;
                break;
            }
        }

        if (shouldPrint) {
            if (count % 2 == 0)
                System.out.println(s.charAt(i) + "- true");
            else
                System.out.println(s.charAt(i) + "- False");
        }

        count = 0;
    }

}

推荐阅读