String Compression

Given an array of characters chars, compress it using the following algorithm:

Begin with an empty string s. For each group of consecutive repeating characters in chars:

  • If the group's length is 1, append the character to s.
  • Otherwise, append the character followed by the group's length.

The compressed string s should not be returned separately, but instead, be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars.

After you are done modifying the input array, return the new length of the array.

Example 1:

Input: chars = ['a','a','b','b','c','c','c']
Output: 6

Approach

Java


public class StringCompression {
    public static void main(String[] args) {
        char[] chars = { 'a''a''b''b''c''c''c' };
        System.out.println(compress(chars));
    }

    static int compress(char[] chars) {
        int i = 0;
        int cnt = 1, n = chars.length;
        int l = 0;
        if (n == 0 || n == 1)
            return n;
        while (i < n - 1) {
            if (chars[i] == chars[i + 1])
                cnt++;
            else {
                chars[l++] = chars[i];
                if (cnt > 1) {
                    String x = String.valueOf(cnt);
                    for (int j = 0; j < x.length(); j++)
                        chars[l++] = x.charAt(j);
                }
                cnt = 1;
            }
            i++;
        }
        chars[l++] = chars[n - 1];
        if (cnt > 1) {
            String x = String.valueOf(cnt);
            for (int j = 0; j < x.length(); j++)
                chars[l++] = x.charAt(j);
        }
        return l;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

int compress(vector<char&chars)
{
    int i = 0;
    int cnt = 1n = chars.size();
    int l = 0;
    if (n == 0 || n == 1)
        return n;
    while (i < n - 1)
    {
        if (chars[i] == chars[i + 1])
            cnt++;
        else
        {
            chars[l++] = chars[i];
            if (cnt > 1)
            {
                string x = to_string(cnt);
                for (int j = 0j < x.size(); j++)
                    chars[l++] = x[j];
            }
            cnt = 1;
        }
        i++;
    }
    chars[l++] = chars[n - 1];
    if (cnt > 1)
    {

        string x = to_string(cnt);

        for (int i = 0i < x.size(); i++)
            chars[l++] = x[i];
    }
    chars.resize(l);
    return l;
}

int main()
{
    vector<charchars = {'a''a''b''b''c''c''c'};
    cout << compress(chars);
    return 0;
}


No comments:

Post a Comment