Wednesday, May 25, 2016

Write a method to perform basic string compression eg. aabcccccaaa.Should become the ouput a2b1c5a3.

Bad Solution:

public String compressBad(String str)
{
  String mystr= "";
  char last=str.charAt(0);
  int count = 1;
  for(int i=1; i< str.length();i++)
  {
    if(str.charAt(i) == last)
    {
      count++;
    
    }
    else
    {
      mystr +=last + "" + count;
      last =str.charAt(i);
      count =1;
    }
  }
  return mystr + last +count ;
}

This code will not be able to handle all the case.Lets take a look at the runtime of this code.

The runtime is o(p+K to the power of 2)

p=size of the original string.
k=number of character sequences.

So if the string is aabccdeea then there are six character sequence  which will be slow the concatenation operates in o(n to the power of 2).

No comments: