Arrays & Hashing

String Challenge 2

Estimated reading: 2 minutes 37 views

Write a function StringChallenge(str) that takes a string as input and returns a compressed version of the string using the Run-length encoding algorithm. This algorithm counts the occurrences of each repeating character and outputs the count followed by that character.

  • Input: "aabbcde"
    Output: 2a2b1c1d1e

  • Input: "wwwbbbw"
    Output: 3w3b1w

The string will not contain any numbers, punctuation, or symbols.

				
					public class StringChallenge {

    // Function to perform Run-Length Encoding on the input string
    public static String runLengthEncode(String str) {
        StringBuilder encoded = new StringBuilder();
        int n = str.length();
        
        for (int i = 0; i < n; i++) {
            int count = 1;
            
            // Count occurrences of the current character
            while (i + 1 < n && str.charAt(i) == str.charAt(i + 1)) {
                count++;
                i++;
            }
            
            // Append the count and character to the result
            encoded.append(count).append(str.charAt(i));
        }
        
        return encoded.toString();
    }

    public static void main(String[] args) {
        // Test cases
        System.out.println(runLengthEncode("aabbcde"));   // Expected Output: 2a2b1c1d1e
        System.out.println(runLengthEncode("wwwbbbw"));   // Expected Output: 3w3b1w
        System.out.println(runLengthEncode("abcccc"));    // Expected Output: 1a1b4c
        System.out.println(runLengthEncode("ggggoppppp")); // Expected Output: 4g1o5p
    }
}

				
			
				
					 // Function to perform Run-Length Encoding using LinkedHashMap
    public static String runLengthEncode(String str) {
        // Use LinkedHashMap to maintain the order of characters
        LinkedHashMap<Character, Integer> charCountMap = new LinkedHashMap<>();
        StringBuilder encoded = new StringBuilder();
        
        // Traverse the string and populate the LinkedHashMap
        for (char ch : str.toCharArray()) {
            charCountMap.put(ch, charCountMap.getOrDefault(ch, 0) + 1);
        }
        
        // Build the encoded string from the LinkedHashMap
        for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
            encoded.append(entry.getValue()).append(entry.getKey());
        }
        
        return encoded.toString();
    }
				
			
Share this Doc

String Challenge 2

Or copy link

CONTENTS