Amazon Interview Question

input string = aabbbccccaaa, maintain the insertion order and output should be a2b3c4a3

Interview Answers

Anonymous

Mar 22, 2017

//input string = aabbbccccaaa, maintain the insertion order and output should be a2b3c4a3 public class Test { public static void process(String mystring) { StringBuilder sb = new StringBuilder(); char[] mychar = mystring.toCharArray(); int count = 1; for(int i=0; i< (mychar.length)-1;i++) { System.out.println("mychar[p1]: "+mychar[i]+" mychar[p2]: "+mychar[i+1]); if(mychar[i] == mychar[i+1]) { count = count+1; System.out.println("count: "+count); } else { sb.append(mychar[i]); sb.append(count); count = 1; } if(i==(mychar.length)-2) { sb.append(mychar[i+1]); sb.append(count); } } System.out.println(sb.toString()); } public static void main(String[] args) { process("aabbbccccaaa"); process("ggggyyynnnkkkkkk"); process("aabbcccdef"); process("abcdefghj"); } }

4

Anonymous

Feb 19, 2019

public class Stringoupt { int count =0; void outputString(String str){ char st = str.charAt(0); for(int i=0;i

1

Anonymous

Nov 25, 2019

a = "aabbbccccaaa" if not a: print ("") if len(a) == 1: print (a+"1") start, end = 0, 1 new_string = a[0] count = 1 while end < len(a): if a[start] == a[end]: count += 1 end += 1 else: new_string += str(count) count = 1 start, end = end, end+1 new_string += a[start] new_string += str(count) print (new_string)

1

Anonymous

Feb 5, 2020

using System; using System.Collections.Generic; namespace Letter__Count_in_String { class Program { static void Main(string[] args) { string original = "aabbbccccaaa"; List result = new List(); char[] arrOriginal = original.ToCharArray(); int count = 1; for (int i = 0; i < arrOriginal.Length; i++) { if ((i < arrOriginal.Length - 1) && (arrOriginal[i] == arrOriginal[i + 1])) { count++; } else { result.Add(arrOriginal[i].ToString() + count.ToString()); count = 1; } } foreach(var a in result) { Console.Write(a); } } } }

Anonymous

May 26, 2020

def compressString(arr): count=1 op="" for i in range(len(arr)): if (i+1)

Anonymous

May 26, 2020

def compressString(arr): count=1 op="" for i in range(len(arr)): if (i+1)

Anonymous

May 18, 2018

a = "aaabbbaaaa" i=0 j=0 fnl_result ="" for item in a: if i== 0: temp = item j = j+1 elif item == temp: j = j+1 elif item!=temp: fnl_result = fnl_result+str(temp)+str(j) j=1 temp = item i=i+1 fnl_result = fnl_result+str(temp)+str(j) print fnl_result #output = a3b3a4

Anonymous

Mar 15, 2017

words = 'aaaabahhhhhaaa' count = 1 answer = '' last_char = None for i, char in enumerate(words): if last_char != None: if char == last_char: count = count + 1 else: answer = '%s%s%d' % (answer, last_char, count) count = 1 if i == (len(words) - 1): print('hi') answer = '%s%s%d' % (answer, last_char, count) last_char = char print(answer)

1