【发布时间】:2020-11-22 16:18:07
【问题描述】:
下面是我删除字符串中连续出现的字符但没有得到预期结果的代码...
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) {
Scanner sc= new Scanner(System.in);
int t=sc.nextInt();
while(t-->0){
String name= sc.next();
char[] c = new char[name.length()];
int j=0;
boolean check=true;
//looping through the array to find duplicates
for(int i=0;i<name.length()-1;i++){
if(name.charAt(i)==name.charAt(i+1)){
continue;
}
else{
c[j]=name.charAt(i);
j++;
check=false;
}
}
//printing the char array
if(check==true){
System.out.println(name);
}else{
for(int i=0;i<j+1;i++){
System.out.print(c[i]);
}
System.out.print(name.charAt(name.length()-1));
System.out.println();
}
}
}
}
预期结果:我的代码应该删除连续出现的字符并打印结果,例如如果输入为caaaabaaad,则输出应为cabad
【问题讨论】:
-
请使用问题主体提出问题并简要介绍您面临的问题?
-
您能描述一下您的代码所面临的问题吗?它是否无法编译,返回与预期不同的结果(对于什么输入,什么是不正确的结果)?
-
我的代码的问题是它不会在多个测试用例的情况下产生结果。代码在产生一些测试用例的输出后停止。
-
请勿在 cmets 中提供此类信息!请阅读minimal reproducible example 并相应地完善您的问题。
-
并提示:为变量使用多个字符。这不是数学公式!代码需要人类阅读,这样的缩写没有意义。
标签: java string algorithm loops duplicates