如何在字符串中删除连续出现的字符?

huangapple go评论58阅读模式
英文:

Debug: How to delete consecutively occurring characters in a string?

问题

以下是我的代码,用于删除字符串中连续出现的字符,但没有得到预期的结果...

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;
            // 遍历数组以查找重复字符
            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;
                }
            }
            // 打印字符数组
            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

英文:

Below is my code to delete consecutively occurring characters in a string but didn't get the expected outcome...

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--&gt;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&lt;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&lt;j+1;i++){
System.out.print(c[i]);
}
System.out.print(name.charAt(name.length()-1));
System.out.println();
}
}
}
}

Expected Outcome : My code is supposed to delete consecutively occurring characters and print the result for example the if input is caaaabaaad the output should be cabad

答案1

得分: 4

你可以使用以下方法:

class GFG {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String name = sc.next();
        String result = "";

        if (name.length() > 0)
            result += name.charAt(0);
        
        // 循环遍历数组以查找重复项
        for (int i = 1; i < name.length(); i++) {
            if (name.charAt(i) == name.charAt(i - 1)) {
                continue;
            } else {
                result += name.charAt(i);
            }
        }
        
        // 打印结果
        System.out.print(result);
    }
}
英文:

You could use this approach:

class GFG {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
String name = sc.next();
String result = &quot;&quot;;
if (name.length() &gt; 0)
result += name.charAt(0);
//looping through the array to find duplicates
for (int i = 1; i &lt; name.length(); i++){
if (name.charAt(i) == name.charAt(i - 1)){
continue;
} else {
result+=name.charAt(i);
}
}
//printing the result
System.out.print(result);
}
}

答案2

得分: 1

以下是您要翻译的内容:

一个替代方法可以是使用Java 8的流。

步骤:

  1. index = 1开始创建一个IntStream,直到末尾。(因为结果值最初等于索引0处的字符)
  2. 如果字符与上次看到的字符不匹配,则将字符添加到最终结果中。
import java.util.*;
import java.util.stream.IntStream;
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();
            String result = IntStream.range(1, name.length())
                                    .mapToObj(i -> name.charAt(i) + "")
                                    .reduce(name.charAt(0) + "", (p, s) -> p.lastIndexOf(s) == p.length() - 1 ? p : p + s);
            System.out.println(result);
        }
    }
}

注意:它使用简单的字符串连接。

英文:

One alternative could be to use java 8 streams.

Steps:

  1. Start an IntStream from index = 1 till the end. (Since result value is initially equal to character at index 0)
  2. Add character to final result if it doesn't match the last seen character.
import java.util.*;
import java.util.stream.IntStream;
class GFG {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        while (t-- &gt; 0) {
            String name = sc.next();
            String result = IntStream.range(1, name.length())
                                    .mapToObj(i -&gt; name.charAt(i) + &quot;&quot;)
                                    .reduce(name.charAt(0) + &quot;&quot;, (p, s) -&gt; p.lastIndexOf(s) == p.length() - 1 ? p : p + s);
            System.out.println(result);
        }
    }
}

Note: It uses simple string concatenation.

答案3

得分: 1

Sure, here's the translated code portion:

好的你的代码存在一些问题

让我们将行号标记如下
```java
01	char[] c = new char[name.length()];
02	int j=0;
03	boolean check=true;
04	//looping through the array to find duplicates 
05	for(int i=0;i&lt;name.length()-1;i++){
06		if(name.charAt(i)==name.charAt(i+1)){
07			 continue;
08		}
09		else{
10		   c[j]=name.charAt(i);
11		   j++;
12		   check=false;
13		}
14	}
15	//printing the char array
16	if(check==true){
17		System.out.println(name);
18	}else{
19		for(int i=0;i&lt;j+1;i++){
20			System.out.print(c[i]);
21		}
22		System.out.print(name.charAt(name.length()-1));
23		System.out.println();
24	}

第一个问题是第1、19、20、21、22行的组合。
我知道这些行是这样放置的,因为你不知道缩减后的字符串长度。所以你通过for循环来复杂化事情,然后从原始字符串中获取最后一个字符。然而,如果你的字符串以两个相同的字符结尾会怎样?

如果我没记错的话,它会打印两次。

第二个问题是你在不同的代码块中处理不同的情况。
这一切都不需要。

所以让我们同时解决所有这些问题。

01	StringBuilder sb = new StringBuilder();
02	int lastChar = 65537; // 这个字符在Java中永远不会存在,因为char是16位的。
03	for (int i = 0; i &lt; name.length(); i++) {
04		char c = name.charAt(i);
05		if (c != lastChar) // 执行int比较,以便选择第一个字符。
06		{
07			sb.append(c);
08			lastChar = c; // 将c扩展为int。
09		}
10	}
11	System.out.println(sb.toString());

我们可以通过使用StringBuilder、ArrayList等来简单解决未知长度的问题。StringBuilder将是最简单的选择。

我们还可以使用int来跟踪我们处理的最后一个字符,而不是使用char。我们在这里使用int而不是char,因为我们需要初始状态不匹配,不管遇到什么字符都应如此。在这里可以使用的另一种技术是使用Character,但这比在原语上使用int扩展要昂贵(堆对象)。

尝试一下,如果你有理解上的困难,请告诉我。


<details>
<summary>英文:</summary>
OK, there are a few problems with your code.
Let&#39;s label the line numbers as below:

01 char[] c = new char[name.length()];
02 int j=0;
03 boolean check=true;
04 //looping through the array to find duplicates
05 for(int i=0;i<name.length()-1;i++){
06 if(name.charAt(i)==name.charAt(i+1)){
07 continue;
08 }
09 else{
10 c[j]=name.charAt(i);
11 j++;
12 check=false;
13 }
14 }
15 //printing the char array
16 if(check==true){
17 System.out.println(name);
18 }else{
19 for(int i=0;i<j+1;i++){
20 System.out.print(c[i]);
21 }
22 System.out.print(name.charAt(name.length()-1));
23 System.out.println();
24 }

The first problem is the combination of lines 1, 19, 20, 21, 22.
I know these lines were put that way because you don&#39;t know the length of the reduced string.  So you complicate things with the for loop and then getting the last character from the original string.  However, what if your string ends with 2 of the same characters?
It will print those twice if I&#39;m not mistaken.
The second problem is that you are handling different cases in different blocks.
None of that is needed.
So let&#39;s handle all of these issues simultaneously.

01 StringBuilder sb = new StringBuilder();
02 int lastChar = 65537; // This char will never exist as char is 16 bits in Java.
03 for (int i = 0; i < name.length(); i++) {
04 char c = name.charAt(i);
05 if (c != lastChar) // perform int comparison so first char will be picked up.
06 {
07 sb.append(c);
08 lastChar = c; // widens c into an int.
09 }
10 }
11 System.out.println(sb.toString());

We can simply solve the unknown length issue by using a StringBuilder, ArrayList, etc... The StringBuilder will be the simplest.
We can also use an int, instead of a char to track our last character processed.  We use an int here instead of a char as we need the initial state to be a no-match irrespective of what character is encountered.  Another technique that can be used here is to use Character, but it will be more expensive (heap object) than using int widening on the primitive.
Try it out and let me know if you have difficulty understanding.
</details>

huangapple
  • 本文由 发表于 2020年8月2日 18:59:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63215192.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定