我希望将字符串模式aabbcc显示为2a2b2c

问题描述 投票:1回答:5

我通过某种浏览获得了输出。但是我无法理解代码背后的逻辑。有没有简单的方法可以做到这一点?

public class LetterCount {
  public static void main(String[] args)
  {
    String str = "aabbcccddd";
    int[] counts = new int[(int) Character.MAX_VALUE];
    // If you are certain you will only have ASCII characters, I would use `new int[256]` instead

    for (int i = 0; i < str.length(); i++) {
        char charAt = str.charAt(i);
        counts[(int) charAt]++;
    }

    for (int i = 0; i < counts.length; i++) {
        if (counts[i] > 0)
            //System.out.println("Number of " + (char) i + ": " + counts[i]);
            System.out.print(""+ counts[i] + (char) i + "");
    }
  }
}    
java
5个回答
1
投票

该代码非常简单。它使用字符的ASCII值索引到存储每个字符频率的数组中。

仅通过对该数组进行迭代即可获得输出,并且该字符的频率大于1,并根据需要在频率后跟字符的输出中进行相应打印。

如果输入字符串具有相同的连续字符,则解决方案可以使用O(1)的空间

例如,在您的字符串aabbcc中,相同的字符是连续的,因此我们可以利用这一事实并计算字符频率并同时打印它。

for (int i = 0; i < str.length(); i++) 
{
 int freq = 1;
 while((i+1)<str.length()&&str.charAt(i) == str.charAt(i+1))
  {++freq;++i}
 System.out.print(freq+str.charAt(i));
}

0
投票

您正在尝试对找到每个字符的次数进行计数。数组由索引引用。例如,小写字母a的ASCII码是整数97。因此,看到字母a的次数计数在counts[97]中。设置counts数组中的每个元素后,您将打印出已找到的元素。


0
投票

这应该有助于您了解如何解决字符串压缩问题的基本思想

import java.util.*;

public class LetterCount {
    public static void main(String[] args) {
        //your input string
        String str = "aabbcccddd";
        //split your input into characters
        String chars[] = str.split("");
        //maintain a map to store unique character and its frequency
        Map<String, Integer> compressMap = new LinkedHashMap<String, Integer>();
        //read every letter in input string
        for(String s: chars) {
            //java.lang.String.split(String) method includes empty string in your 
            //split array, so you need to ignore that
            if("".equals(s))
                continue;
            //obtain the previous occurances of the character
            Integer count = compressMap.get(s);
            //if the character was previously encountered, increment its count
            if(count != null)
                compressMap.put(s, ++count);
            else//otherwise store it as first occurance
                compressMap.put(s, 1);
        }
        //Create a StringBuffer object, to append your input
        //StringBuffer is thread safe, so I prefer using it
        //you could use StringBuilder if you don't expect your code to run
        //in a multithreaded environment
        StringBuffer output = new StringBuffer("");
        //iterate over every entry in map
        for (Map.Entry<String, Integer> entry : compressMap.entrySet()) {
            //append the results to output
            output.append(entry.getValue()).append(entry.getKey());
        }
        //print the output on console
        System.out.println(output);
    }
}

0
投票

有3个条件需要注意-

  • if(s.charAt(x)!= s.charAt(x + 1)&& count == 1)打印计数器和字符
  • 如果(s.charAt(x)== s.charAt(x + 1)==>增加计数器
  • if(s.charAt(x)!= s.charAt(x + 1)&& count> = 2)==>重置为计数器1。

    {int count= 1;
    int x;
    for (x = 0; x < s.length() - 1; x++) {
        if ( s.charAt(x) != s.charAt(x + 1) && count == 1) {
            System.out.print(s.charAt(x));
            System.out.print(count);
        }
    
        else if ( s.charAt(x)== s.charAt(x + 1)) {
            count++;
        }
    
        else if ( s.charAt(x) != s.charAt(x + 1) && count >= 2) {
            System.out.print(s.charAt(x));
            System.out.print(count);
            count = 1;
        } 
    }
    System.out.print(s.charAt(x));
    System.out.println(count);}
    

0
投票
class Solution {
  public String toFormat(String input) {
    char inChar[] = input.toCharArray();
    String output = "";
    int i;
    for(i=0;i<input.length();i++) {
      int count = 1;
      while(i+1<input.length() && inChar[i] == inChar[i+1]) {
        count+=1;
        i+=1;
      }
      output+=inChar[i]+String.valueOf(count);
    }
    return output;
  }
  public static void main(String[] args) {
    Solution sol = new Solution();
    String input = "aaabbbbcc";  
    System.out.println("Formatted String is: " + sol.toFormat(input)); 
  }
}

0
投票
q="aabbcc"
a=""
count=1
if len(q)>1:
    for i in range(1,len(q)):
        if q[i-1]==q[i]:
            count+=1
        else:
            a+=str(count)+q[i-1]
            count=1
    a+=str(count)+q[i]
    print(a)
else:
    i=0
    a+=str(count)+q[i]
    print(a)
© www.soinside.com 2019 - 2024. All rights reserved.