简体   繁体   English

Java字符串压缩输出错误的字符串。 我在这里想念什么?

[英]Java string compression is printing wrong string. What am I missing here?

I have a string "aaabbaaaavvvd", it should be compressed to a3b2a4v3d But when I run my code it prints out b3a2v4d3 我有一个字符串“ aaabbaaaavvvd”,应该将其压缩为a3b2a4v3d,但是当我运行我的代码时,它会打印出b3a2v4d3

Strangely, it starts with b instead of a 奇怪的是,它以b而不是a开头

public class compression {
    public String compress(String str){
        char chararr[] = str.toCharArray();
        StringBuilder sb = new StringBuilder();
        int count=1;
        char previous = chararr[0];
        for(int i=1; i<chararr.length; i++) {
             char current = chararr[i]; 
             if(current == previous){
                 count++;
             } else {
                 sb.append(current).append(count);
                 count = 1;
             }
             previous = current;
        }
        System.out.println(sb.toString());
        return sb.toString();
    }

    public static void main(String args[]){
        compression test = new compression();
        String str = "aaabbaaaavvvd";
        test.compress(str);
    }
}

Error on line: 在线错误:

sb.append(current).append(count);

Think about the if statement 考虑一下if语句

if(current == previous){
    count++;
} else {
    sb.append(current).append(count);
    count = 1;
}

As your code steps through each character, the if statement is only false if the current character is not equal to the last (ie the current character is the start of a new sequence of characters). 当您的代码遍历每个字符时,如果当前字符不等于最后一个字符(即, 当前字符是新字符序列的开始),则if语句仅为false。

Stepping through one-by-one: 一步一步走:

Index 1: previous == 'a', current == 'a', if-statement: true - increments
Index 2: previous == 'a', current == 'a', if-statement: true - increments
Index 3: previous == 'a', current == 'b', if-statement: false - prints and reset

Note how upon the third index, current is b rather than the required character a , outputting b3 as opposed to a3 . 请注意,在第三个索引上, currentb而不是必需的字符a ,从而输出b3而不是a3

Replace the append chain with previous to fix: 替换追加链previous解决:

if(current == previous){
    count++;
} else {
    sb.append(previous).append(count);
    count = 1;
}

You have 3 issues: 您有3个问题:

  1. When current == previous you should add 1 to counter and then continue current == previous您应该在计数器上加1,然后continue
  2. When you exit the loop - print the last char that you process 退出循环时-打印您处理的最后一个字符
  3. You should append the previous char - not the current sb.append(previous) 您应该附加上一个字符-而不是当前sb.append(previous)

your code should look like this: 您的代码应如下所示:

        public String compress(String str){
        char chararr[] = str.toCharArray();
        StringBuilder sb = new StringBuilder();
        int count=1;
        char previous = chararr[0];
        for(int i=1; i<chararr.length; i++) {
            char current = chararr[i];
            if(current == previous){
                count++;
                continue;
            } else {
                sb.append(previous).append(count);
                count = 1;
            }
            previous = current;
        }

        sb.append(previous).append(count);
        System.out.println(sb.toString());
        return sb.toString();
    }

This code sample works. 此代码示例有效。 I have changed sb.append(current) to sb.append(previous) and added a sb.append(previous).append(count) outside the for loop to account for the last character 我已经将sb.append(current)更改为sb.append(previous),并在for循环外添加了sb.append(previous).append(count)以解决最后一个字符

public class compression {
public String compress(String str){
    char chararr[] = str.toCharArray();
    StringBuilder sb = new StringBuilder();
    int count=1;
    char previous = chararr[0];
    for(int i=1; i<chararr.length; i++) {
         char current = chararr[i]; 

         if(current == previous){
             count++;
         } else {
             sb.append(previous).append(count);
             count = 1;
         }

         previous = current;
    }

    sb.append(previous).append(count);

    System.out.println(sb.toString());
    return sb.toString();
}

public static void main(String args[]){
    compression test = new compression ();
    String str = "aaabbaaaavvvd";
    test.compress(str);
}

} }

Try this: 尝试这个:

public class Compression {
    public String compress(String str) {
        char chararr[] = str.toCharArray();
        StringBuilder sb = new StringBuilder();
        int count = 0;
        char previous = chararr[0];
        for (int i = 0; i < chararr.length; i++) {
            char current = chararr[i];
            if (current == previous) {
                count++;
            } else {
                sb.append(previous);
                if (count != 1) {
                    sb.append(count);
                }
                count = 1;
            }
            previous = current;
        }

        sb.append(previous);
        if (count != 1) {
            sb.append(count);
        }
        return sb.toString();
    }

    public static void main(String args[]) {
        Compression test = new Compression();
        System.out.println(test.compress("aaabbaaaavvvd"));
        System.out.println(test.compress("aaabbaaaavvvdddd"));
    }
}

Output: 输出:

a3b2a4v3d a3b2a4v3d
a3b2a4v3d4 a3b2a4v3d4

Try something like below: 尝试如下所示:

public String compress(String str){

    String result="";
    StringBuilder sb = new StringBuilder(str);


    while(sb.length() != 0){
        int count = 0;
        char test = sb.charAt(0);
        while(sb.indexOf(test+"") != -1){
            sb.deleteCharAt(sb.indexOf(test+""));
            count++;
        }
        result=result+test+count;
    }
    System.out.println(result); 

    return sb.toString();
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将字符串中的第一个字母大写。 我究竟做错了什么? - Capitalizing the first letter in a string. What am I doing wrong? 当我在 Java 中读取 API 时,我在字符串中使用 ÃŽ 代替 Î。 我该怎么办? - When I am reading a API in java I get ÃŽ in place of Î in a string. What should I do? 我在这里想念什么? - What am I Missing here? 试图让我的弦向左旋转。 我在这里做错了什么? - Trying to get my string to rotate left. What am I doing wrong here? 我在做什么错(Java)十进制转换为二进制 - What am I Doing Wrong Here(Java) Decimal to Binary Java读/写:我在这里做错了什么? - Java read/write: what am I doing wrong here? Java泛型-我在这里做错了什么? - Java Generics - What am I doing wrong here? 我试图将一个字符串字符插入另一个字符串。 如何在Java中实现? - I am trying to insert a string character to another string. How can I achieve it in java? 当尝试根据给定查询查找给定字符串中的子字符串计数时,有人能告诉我我在 Java 代码中做错了什么吗? - Can someone tell me what am I doing wrong here in my Java code when trying to find count of substrings in given string according to given queries? BeanCreationException 和 NoClassDefFoundError:我在这里缺少什么? - BeanCreationException and NoClassDefFoundError : What am I missing in here?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM