Calculate and replace repeated characters in a string with their number of occurrences.
Example :
aaaggbbbbc
3a2g4b1c

import java.lang.*;
import java.util.*;

public class Solution {
    public String dupString(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        Character cur = s.charAt(0);
        int count = 1;
        for (int i = 1; i < s.length(); i++) {
            if (cur == s.charAt(i)) {
                count++;
                continue;
            } else {
                sb.append(count).append(cur);
                count = 1;
                cur = s.charAt(i);
            }
        }
        sb.append(count).append(cur);
        return sb.toString();
    }
    public static void main(String[] args) {
        Solution sol = new Solution();
        String s1 = "aaaaaaa";
        String s2 = "abbbbbbaaa";
        String s3 = "a";
        String s4 = "bcdd";
        System.out.println(sol.dupString(s1));
        System.out.println(sol.dupString(s2));
        System.out.println(sol.dupString(s3));
        System.out.println(sol.dupString(s4));
    }
}
Advertisements