String Encoding | Goldman Sachs Coding Question 1 | Placement Papers

 String Encoding

Goldman Sachs Coding Question


Encode a given string by collapsing consecutive instances of a single character into two pieces of information: the number of instances and the character. Note that even single characters should be run length encoded. If the string is empty, return an empty string. Your implementation should work on all alphanumeric characters.


Complete the collpaselnput function which takes a string input as a parameter and returns the compressed string.


Sample Input

GGGGGrrrrrrrrrrrrrrt


Sample Output 

5G14r1t


Explanation

There are 5 'G' characters then there are 14 'r's then there is 1 't'



Java Solution

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {
    /*
     * Complete the 'collapseString' function below.
     *
     * The function is expected to return a STRING.
     * The function accepts STRING inputString as parameter.
     */

    public static String collapseString(String inputString) {
        if(inputString == null){
            return null;
        }
        char tempChar = inputString.charAt(0);
        int count = 0;
        StringBuilder sb = new StringBuilder();
        for(char ch : inputString.toCharArray()){
            if(ch == tempChar){
                count++;
            } else {
                sb.append(count);
                sb.append(tempChar);
                tempChar = ch;
                count = 1;
            }
        }
        sb.append(count);
        sb.append(tempChar);
        
        return sb.toString();   
    }
}
public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String inputString = bufferedReader.readLine();

        String result = Result.collapseString(inputString);

        bufferedWriter.write(result);
        bufferedWriter.newLine();
        bufferedReader.close();
        bufferedWriter.close();
    }
}



Post a Comment

0 Comments