Friday, December 12, 2014

Count and Say

Google has an upgraded version of LeetCode's Count and Say problem.

Write a function that given a sequence and a number b between [-10,10] return a new sequence. Sequences are generated by this: http://en.wikipedia.org/wiki/Look-and-say_sequence a number b if equal to 0 the function will return the input sequence Valid sequences: 1 11 21 1211 111221 ... Example: input: 1211, +1 output: 111221 Example: input: 111221, -1 output: 1211 

The problem itself is not a hard one. However, I couldn't figure out a way to use one loop for both b greater than 0 or less than 0. Is there one?

public class CountSay {
 public String countandsay(String s, int b)
 {
  if (s == null)
   return "";
  if (b == 0)
   return s;
  
  StringBuilder prev = new StringBuilder(s);
  StringBuilder curr = new StringBuilder();
  
  for (int i = 0; i < Math.abs(b); i++)
  {
   if (prev.length() == 1)
    return "";
   int index = 0;
   curr = new StringBuilder();
   if (b < 0)
   {
    while (index < prev.length())
    {
     int count = Character.getNumericValue(prev.charAt(index));
     index++;
     char num = prev.charAt(index);
     for (int j = 0; j < count; j++)
      curr.append(num);
     index++;
    }
   }
   else
   {
    while(index < prev.length())
    {
     char num = prev.charAt(index);
     int count = 1;
     while (index < prev.length() - 1 && prev.charAt(index) == prev.charAt(index + 1))
     {
      count++;
      index++;
     }
     curr.append(count);
     curr.append(num);
     index++;
    }
   }
   prev = curr;
  }
  return curr.toString();
 }

}

No comments:

Post a Comment