Tuesday, August 11, 2015

Codility - Correct an incorrect License Key

Problem

Dashes have been inserted at the wrong places to generate an incorrect license key s. You need to correct the string such that a dash will be inserted after every k characters and make the string uppercase with complexity O(n). int k, and String s have been provided as inputs. You need to return the corrected license key

Solution

String solution(String a, int k)
 {
  StringBuffer res = new StringBuffer();
  int i, counter=0;
  for(i=0; i< a.length(); i++)
  {
   if(a.charAt(i) != '-') 
   {
    counter++;
    if((counter%k) == 1 && res.length() > 0) 
     {
      res.append("-");
      counter = 1;
     }
    res.append(Character.toUpperCase(a.charAt(i)));
   }
  }
  
  return res.toString();
 }

No comments:

Post a Comment