Amazon Interview Question
Software Development ManagersCountry: United States
can we do without recursion?
static string Compress(string s)
{
var ch = s[0];
var count = 1;
var output = new StringBuilder();
for(var i=1;i<s.Length;i++)
{
if(s[i] == ch)
{
count++;
}
else
{
output.Append(count == 1 ? ch.ToString() : ch + count.ToString());
count = 1;
ch = s[i];
}
}
output.Append(count == 1 ? ch.ToString() : ch + count.ToString());
return output.ToString();
}
@S.Abakumoff
I don't see any recursion in the solution provided by xdoer, can u explain what you meant by recursion?
is the characters coming in an alphabet order? when the input is AABBCCDDAA the output would be A2B2C2D2A2, not A4B2C2D2
Solution does not work if last char in input string is a different from last but one char (e.g jjjjjjjjddddddddddaaaak)
Need to add
if(str.charAt(str.length()-1)!=str.charAt(str.length()-2))
System.out.println("====="+t_str+str.charAt(str.length()-1)+"1");
function compress(string toCompress){
if(toCompress.length() < 2){
return toCompress;
}
string compressed = "";
char[] charList = toCompress.toCharArray();
char currentChar = charList[0];
int currentCount = 1;
for(int i = 1; i < charList.length; i++){
if(charList[i] == currentChar){
currentCount++;
}else{
compressed += currentChar + currentCount;
currentChar = charList[i];
currentCount = 1;
}
}
return compressed;
}
private static String compress(String toCompress){
if(toCompress.length() < 2){
return toCompress;
}
String compressed = "";
char[] charList = toCompress.toCharArray();
char currentChar = charList[0];
int currentCount = 1;
for(int i = 1; i < charList.length; i++){
if(charList[i] == currentChar){
currentCount++;
}else{
compressed += "" + currentChar + "" + currentCount;
currentChar = charList[i];
currentCount = 1;
}
}
compressed += "" + currentChar + "" + currentCount;
return compressed;
}
static String compress(String string){
int count=0;
char prevChar= string.charAt(0);
String result="";
char [] charArray=string.toCharArray();
for(char c: charArray){
if(c==prevChar){
count++;
}else{
if(count==1){
result= result.concat(new StringBuilder(1).append(c).toString());
}else{
result= result.concat(prevChar+ Integer.toString(count));
}
count=1;
prevChar=c;
}
}
result=result.concat(string.charAt(string.length()-1)+ Integer.toString(count));
return result;
}
public class CompressString {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//AAACCCBBD to A3C3B2D
String str="ABC";
StringBuffer sb=new StringBuffer();
int charcounter=1;
char previouschar=str.charAt(0);
if(str.length()==1){
sb.append(previouschar);
}
if(str.length()>1){
for(int icounter=1;icounter<str.length();icounter++){
if(str.charAt(icounter)==previouschar){
charcounter++;
}
else{
sb.append(previouschar);
if(charcounter!=1){
sb.append(charcounter);
}
charcounter=1;
previouschar=str.charAt(icounter);
}
}
sb.append(previouschar);
if(charcounter!=1){
sb.append(charcounter);
}
}
System.out.println(sb);
}
}
public static void compressString(String inp) {
StringBuilder out = new StringBuilder();
int count = 1;
for(int i=0;i<inp.length();i++)
{
if(i<inp.length()-1 && inp.charAt(i) == inp.charAt(i+1)) {
count++;
continue;
}
out.append(inp.charAt(i));
if(count>1)
out.append(count);
count=1;
}
System.out.println(out.toString());
}
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
int main()
{
char str[] = "AAAAAABBBBBCCCHHHDADAS";
int i=0, j=0, count=0;
char c;
for(i=0;i<strlen(str);i++)
{
char c = str[i];
while(c == str[i])
{
count++;
i++;
}
i--;
str[j++]=str[i];
itoa(count,(str+j),10);
str[j+1] = " ";
j++;
count = 0;
}
str[j] = '\0';
printf("\n%s",str);
return 0;
}
JavaScript solution - O(n)
function compress(content) {
var character, count, i, result = [];
for (i = 0; i < content.length;) {
character = content.charAt(i);
result.push(character);
++i;
count = 1;
while (content.charAt(i) === character) {
++count;
++i;
}
if (count > 1) {
result.push(count);
}
}
return result.join('');
};
void Main()
{
string data = "AABCDDDDEEFFF";
Console.WriteLine("OLD {0} : NEW {1}", data, BuildStringRepresentation(data));
}
// Define other methods and classes here
string BuildStringRepresentation(string data) {
StringBuilder s = new StringBuilder();
if(data.Length <= 1) {
return data;
}
int i = 0, count = 0;
char ch;
while(i < data.Length) {
ch = data[i];
count = 0;
while(i < data.Length - 1 && data[++i] == ch) {
count++;
}
if(i == data.Length - 1) {
i++;
}
s.Append(ch);
if(count > 0) {
s.Append(count+1);
}
}
return s.ToString();
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void addcount(int, int, char*);
int main(int argc, char **argv)
{
char *string = argv[1];
char *newstring;
int len = strlen(string);
newstring = (char *)malloc(2*len);
int i,j = 0;
int count = 0;
char prevch;
char currch;
while(string[i] != '\0')
{
currch = string[i];
if(currch == prevch || i == 0)
{
count++;
i++;
prevch = currch;
continue;
}
/*else if(currch != prevch && prevch == NULL)
{
count++;
i++;
prevch = currch;
continue;
}*/
else{
newstring[j] = prevch;
addcount(j+1, count, newstring);
j+=2;
count = 1;
i++;
prevch = currch;
continue;
}
}
newstring[j] = prevch;
addcount(j+1, count, newstring);
//newstring[j+1] = itoa(count);
newstring[j+2] = '\0';
printf("this is original string: %s\n", string);
printf("this is new string: %s\n", newstring);
return;
}
void addcount(int j, int count, char *nstring)
{
int chararray[10] = {48,49,50,51,52,53,54,55,56,57};
if(count < 10)
{
nstring[j] = chararray[count];
}else if(10 < count < 100)
{
int n1 = count/10;
int n2 = count%10;
nstring[j++] = chararray[n1];
nstring[j++] = chararray[n2];
}
}
scala> def pack(s: String, r: String): String = s match {
| case "" => r
| case _ => val (x,y) = s.tail.span(_ == s.head)
| val v = if(x == "") s.head.toString else s.head+(x.length+1).toString
| pack(y,r+v)
| }
pack: (s: String, r: String)String
scala> pack("AAABBCCCDA","")
res13: String = A3B2C3DA
This is Java Program
inArr is we can create the char array and outPut array.
public class CompressingArray {
int count1=1,i, count2, count3;
char[] inArr = { 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'X', 'X', 'T', 'T',
'T', 'T' };
char[] outArr = new char[20];
public char[] compress() {
for ( i = 0; i < (inArr.length-1); i++) {
if (inArr[i] == inArr[(i + 1)]) {
count1++;
//System.out.println(count1);
} else {
System.out.print(""+(char)inArr[i]+count1);
count1 = 1;
}
}System.out.print(""+(char)inArr[i]+count1);
return outArr;
}
public static void main(String[] args) {
new CompressingArray().compress();
}
}
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;
public class Test {
static LinkedHashMap<String, Integer> ht = new LinkedHashMap<String, Integer>();
public static void main(String[] args) {
String array[] = { "A", "A", "A", "C", "C", "C", "B", "B", "D" };
int length = array.length;
for (int i = 0; i < length; i++) {
String value = array[i];
if (ht.containsKey(value)) {
int count = ht.get(value);
ht.put(value, ++count);
} else {
ht.put(array[i], 1);
}
}
int k = 0;
Set set = ht.keySet(); // get set-view of keys
Iterator itr = set.iterator();
while (itr.hasNext()) {
String str = (String) itr.next();
array[k] = str;
k++;
array[k] = ht.get(str).toString();
k++;
}
array = Arrays.copyOf(array, k - 1);
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
}
Here is the solution for this problem using c/cpp. I checked this for few condition, please let me know if it is wrong...
int CheckString(const char *pcString)
{
if( pcString == NULL )
return 1;
char cCurr;
char cPrev;
int iCounter = 0;
int iRepeatCount = 1;
while( pcString[iCounter] != '\0' )
{
cPrev = pcString[iCounter];
iRepeatCount = 1;
for(int iCharTraverse = iCounter + 1; pcString[iCharTraverse] == cPrev; iCharTraverse ++)
{
cCurr = pcString[iCharTraverse];
if( cPrev == cCurr )
{
iRepeatCount ++;
iCounter++;
}
}
if( iRepeatCount > 1)
printf("%c%d", cPrev, iRepeatCount);
else
printf("%c", cPrev);
iCounter++;
}
return 0;
}
int main(int argc, CHAR** argv)
{
CheckString("AAACCCBBD");
//output will be : A3C3B2D
return 0;
}
#include<stdio.h>
#include<string.h>
int main()
{
char str[100],c;
int i,len,idx=0,count=1;
scanf("%s",str);
len=strlen(str);
c=str[0];
for(i=1;i<len;i++)
{
if(str[i]==c)
++count;
else
{
str[idx++]=c;
if(count>1)
str[idx++]=count+'0';
c=str[i];
count=1;
}
}
str[idx++]=c;
if(count>1)
str[idx++]=count+'0';
str[idx]='\0';
printf("\n%s",str);
return 0;
}
def compressString(string):
count = 1
re = ''
tag = string[0]
for i in range(1, len(string)):
if tag == string[i] and i != len(string) - 1:
count += 1
elif i == len(string) - 1:
if tag == string[i]:
count += 1
re = re + tag + str(count)
else:
re = re + tag + str(count) + string[i]
print id(re)
else:
re = re + tag + str(count)
count = 1
tag = string[i]
return re if len(re) < len(string) else string
print compressString('aaaaaaadddddddddkkkkkkkk')
#include <string>
#include <vector>
#include <map>
using namespace std;
string compress(const string& in)
{
map<char,int> m;
map<char,int>::iterator it;
vector<char> v;
char buf[10];
string out;
size_t s = in.length();
for(size_t i=0; i<s; i++)
{
char ch = in[i];
it = m.find(ch);
if(it != m.end())
it->second++;
else
{
m.insert(pair<char,int>(ch,1));
v.push_back(ch);
}
}
for(vector<char>::iterator vi=v.begin(); vi<v.end(); vi++)
{
char ch = *vi;
it = m.find(ch);
sprintf_s(buf,10,"%c%i",ch,it->second);
out += buf;
}
return out;
}
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
string str;
cout<<"Enter string to compress: ";
cin>>str;
int j=1;
char c = str[0];
string op;
op += c;
char buff[5];
for(int i=1;i<str.length();++i)
{
if(c!=str[i])
{
sprintf(buff,"%d",j);
op += buff;
op +=str[i];
j = 1;
}
else
{
++j;
}
c = str[i];
}
sprintf(buff,"%d",j);
op += buff;
cout<<op<<endl;
return 0;
}
void stringCompress(String a){
int size = a.length();
System.out.println("Size = " + size);
char chararray[] = a.toCharArray();
char char1, char2;
int charlength = 1 , i=1;
if(size == 0) {
System.out.println("No characters present");
return;
}
if(size == 1){
System.out.println(chararray[0]+"1");
return;
}
char1 = chararray[0];
char2 = chararray[1];
while(i<size) {
char2 = chararray[i];
if(char1 == char2) {
charlength++;
}
else {
System.out.print(char1+""+charlength);
charlength = 1;
}
char1 = char2;
i++;
}
if(char1==char2) {
System.out.print(char1+""+charlength);
}
}
string compress(string s)
{
string result;
int count = 1;
for (int i = 0; i < s.length(); i++) {
if (s[i] == s[i + 1]) {
count++;
continue;
} else {
result = result + s[i];
char n[20];
sprintf(n, "%d", count);
result = result + n;
count = 1;
}
}
if (result.length() > s.length())
return s;
else
return result;
}
public void compressString(String value){
char[] values = value.toCharArray();
StringBuilder sb = new StringBuilder("");
char prev = values[0];
int count = 1;
for(int i =1 ; i<= values.length ; i++){
if(i<values.length){
if(values[i] == prev){
count++;
}
else{
sb.append(prev);
if(count > 1){
sb.append(count);
}
prev = values[i];
count = 1;
}
}
else{
sb.append(prev);
if(count > 1){
sb.append(count);
}
}
}
System.out.println(sb.toString());
}
PrintCompressed("AAACCCBBDXXXXEEEE!!!!GGGGAQ!WDFGGGGGH");
Result: A3C3B2DX4E4!4G4AQ!WDFG5H
public void PrintCompressed(string chars)
{
var charArray = new List<char>();
var countArray = new List<int>();
//add the first
charArray.Add(chars[0]);
countArray.Add(1);
//loop through the rest
for (int c = 1; c < chars.Length; c++)
{
if (chars[c - 1] != chars[c])
{
charArray.Add(chars[c]);
countArray.Add(1);
}
else
{
countArray[charArray.Count() - 1]++;
}
}
//build the string to print
var stringBuilder = new StringBuilder();
for (int i = 0; i < charArray.Count(); i++)
{
stringBuilder.AppendFormat("{0}{1}", charArray[i], countArray[i] > 1 ? countArray[i].ToString() : "");
}
//print
Console.WriteLine(stringBuilder.ToString());
}
from collections import OrderedDict
def count_chars(s):
d = OrderedDict()
for i in range(len(s)):
if s[i] in d:
d[s[i]] += 1
else:
d[s[i]] = 1
return d
def combine_str_count(d):
res = ''
for k, v in d.items():
# handle special case of not printing 1
if v == 1:
v = ''
res = ''.join([res, str(k), str(v)])
return res
def compress_string(s):
d = count_chars(s)
return combine_str_count(d)
if __name__ == "__main__":
print(compress_string("AAACCCBBD"))
from collections import OrderedDict
def count_chars(s):
d = OrderedDict()
for i in range(len(s)):
if s[i] in d:
d[s[i]] += 1
else:
d[s[i]] = 1
return d
def combine_str_count(d):
res = ''
for k, v in d.items():
# handle special case of not printing 1
if v == 1:
v = ''
res = ''.join([res, str(k), str(v)])
return res
def compress_string(s):
d = count_chars(s)
return combine_str_count(d)
if __name__ == "__main__":
print(compress_string("AAACCCBBD"))
public static String compress(final String str) {
final StringBuilder builder = new StringBuilder();
if ((str == null) || str.isEmpty()) {
return "0";
}
builder.append(str.charAt(0));
int count = 1;
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i) == str.charAt(i - 1)) {
count++;
} else {
builder.append(count);
builder.append(str.charAt(i));
count = 1;
}
}
builder.append(count);
return builder.toString();
}
void compress(char *str,int size)
{
if(!(*str))
return;
int index=0;
for(int i=0;i<(size-1);i++)
{
int j=1;
str[index++]=str[i];
while(str[i]==str[i+1])
{
i++;
j++;
}
if(j>1)
str[index++]=j+48;
}
memset(str+index,'\0',size-index);
}
Those who marked this solution negative can you please tell me for which input it is getting failed.. Tested some input getting right answer.
A little verbose, but hopefully it is easier to understand.
- xdoer February 18, 2013