Online Judge Solutions

Wednesday, February 25, 2015

Rotate Array

Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
class Solution {
    void rotateHelper(int A[], int k, int n)
    {
        int i = 0;
        while(i + k < n) 
        {
            int count = 0;
            for(; i+k < n; i++) {
                int t = A[i];
                A[i] = A[i+k];
                A[i+k] = t;
                count++;
            }   
            
            k = k - count % k; 
        }
    }


public:
    /**
     * param A: A string
     * param offset: Rotate string with offset.
     * return: Rotated string.
     */
     void rotate(int A[], int n, int k) {
        if (n < 2) return ;
        int K = n - k % n;
        
        rotateHelper(A, K, n); 
    }
};

Tuesday, February 17, 2015

Regular Expression match with * and +

This one was from Facebook Seattle Onsite (asked by an Indian guy :)) Given a source string (doesn't contain '*' or '+') and a pattern string (may contain zero or more '+' or '*'). Check if the source matches the pattern. '*' mean the letter before it can appear 0 or more times '+' mean the letter before it can appear 1 or more times ie: aab matches a+b or a*b abc doesn't match ad+bc but matches ad*bc.


#include "stdafx.h"
#include "assert.h"

 bool isMatch(const char *s, const char *p) {
     if (!*p) return !*s;
     
     if (*(p+1) != '*' && *(p+1) != '+') 
         return (*s == *p) && isMatch(s+1, p+1);

      if ( *(p+1) == '+') {
          if (*s != *p)  return false;
          ++s;
      }

      while( *s == *p) {
           if (isMatch(s, p+2)) return true;
           s++;
       }
       
       return isMatch(s, p+2);
 }

int _tmain(int argc, _TCHAR* argv[])
{
    assert(isMatch("", ""));
    assert(!isMatch("a", ""));
    assert(!isMatch("aa", ""));
    assert(!isMatch("aaa", ""));
    assert(!isMatch("", "a"));
    assert(!isMatch("", "aa"));
    assert(!isMatch("", "aaa"));
    assert(!isMatch("a", "aa"));
    assert(!isMatch("aa", "a"));    
    assert(isMatch("a", "a"));
    assert(isMatch("ab", "ab"));
    assert(isMatch("a", "a*"));
    assert(isMatch("a", "a+"));
    assert(isMatch("aa", "a*"));
    assert(isMatch("aa", "a+"));
    assert(isMatch("aaa", "a+"));
    assert(isMatch("aaa", "a+"));
    assert(!isMatch("aab", "a+"));
    assert(!isMatch("aab", "a+"));
    assert(isMatch("aab", "a*b"));
    assert(isMatch("aab", "a+b"));
    assert(isMatch("aab", "a*b+"));
    assert(isMatch("aab", "a+b*"));
    assert(isMatch("aabbc", "a+b+c"));
    assert(isMatch("aabbc", "a+b*c"));
    assert(isMatch("aabbc", "aa*b*c"));
    assert(isMatch("aabbc", "aa+bb+c"));
 return 0;
}