Title: String compression: Write a method to implement basic string compression using the number of repeated characters. For example, the string aabccCCCAaa becomes a2b1C5A3. If the compressed string is not shorter, the original string is returned. You can assume that the string contains only upper - and lower-case English letters (a to Z). Example 1: Input: "aabCCCCCAaa" Output: "a2b1C5A3" Example 2: Input: "abbccd" Output: "abbccd" Description: The length of "abbccd" is longer than the original string. Hint: The string length is in the range of [0, 50000]. Double pointerCopy the code

1. Code by compressString.java:

package com.yuhl.right.leetcode;

/ * * *@author yuhl
 * @Date 2020/10/25 8:48
 * @Classname CompressString
 * @DescriptionString compression * String compression: Write a method to implement basic string compression using the number of repetitions of characters. For example, the string aabccCCCAaa becomes a2b1C5A3. If the compressed string is not shorter, the original string is returned. You can assume that the string contains only upper - and lower-case English letters (a to Z). * * Example 1: * Input: "aabccCCCAaa" * Output: "a2b1C5A3" * * Example 2: * Input: "abbccd" * Output: "abbccd" * Explanation: "ABbccd" is compressed to "A1B2C2D1", which is longer than the original string. * Hint: * The string is in the range of [0, 50000]. * /
public class CompressString {
    public static void main(String[] args) {
        String s = "aabcccccaaa";
        String res = compressString(s);
        System.out.println(res);
    }

    public static String compressString(String S) {
        / / double pointer
        int N = S.length();
        int i = 0;
        StringBuilder sb = new StringBuilder((int)(N * 0.75));
        while (i < N) {
            int j = i;
            while (j < N && S.charAt(j) == S.charAt(i)) {
                j++;
            }
            sb.append(S.charAt(i));
            sb.append(j - i);
            i = j;
        }

        String res = sb.toString();
        if (res.length() < S.length()) {
            return res;
        } else {
            returnS; }}}Copy the code

2. Execution Results:

"C: \ Program Files \ Java \ jdk1.8.0 _201 \ bin \ Java exe" 
a2b1c5a3
Copy the code