java - 删除字符串中的偶数对字符从字符串中重复出现字符 - java
问题描述
我是java初学者,我有这个问题:
**Q01 [ 7分] 编写一个java程序,以字符串为输入,使用EvenPairs(str)方法检查每个字符(即Alphabet)是否存在偶数对。示例测试用例
输入:“3gy41d21y363”
输出:
- 3 – 错误
- g – 错误
- 是 - 真
- 4 – 错误
- 1 – 真
- d – 错误
正如您在输出中看到的那样,即使重复出现每个字符也只打印一次,直到这一步我才解决了问题
这是我的代码:
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-错误
等待你的帮助!!谢谢你
解决方案
这是代码。基本上所有字符都算完之后。我向后看,以确保在打印之前它不是重复的。这里有很大的优化空间,比如在计数之前进行检查,或者不计算所有字符,您可以只计算 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;
}
}
推荐阅读
- android-studio - 如何修复“预期类型不匹配:推断类型为 GoogleSignInAccount?但预期为 GoogleSignInAccount”错误?
- amazon-web-services - 自动将存储桶策略应用于所有新上传的文件
- asp.net-core - ASP.net Core:如何将标头值注入自定义记录器?
- json - 从 JSON 解析时未定义的对象 - React
- python - Apache 上的 Django 应用程序出现 403 禁止错误
- python - 带银行的随机硬币翻转程序
- docker - PhpStorm + Docker + Composer
- apexcharts - 如何访问 Apexchart 的 dataPointSelection 函数的值
- c# - c#根据条件用列填充组合框
- java - 在这种情况下如何解释 NoClassDefFoundError?