Monday, May 16, 2016

#codingexercise

Given n non-negative integers in array representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

int GetArea(List<int> height)
{
int result = 0;
int n = height.Count
if (height == null || n <=2)
    return height;
var left = new List<int>();
var right = new List<int>();
// scan left
int max = height[0];
left[0] = height[0];
for (int i = 1; i < n; i++)
{
if (height[i] < max){
left[i] = max;
}else{
left[i] = height[i];
max = height[i];
}
}
// scan right
max = height[n - 1];
right[n-1] = height[n-1];
for (int i = n-2; i>=0; i--)
{
if (height[i] < max){
right[i] = max;
}else{
right[i] = height[i];
max = height[i];
}
}
for (int i =0; i < n ; i++)
{
result += Math.min(left[i],right[i]) - height[i];
}
return result;
}

int match(char* regexp, char* text)
{
if (regexp[0] == '^')
    return matchHere(regexp+1, text);
do {
if (matchHere(regexp, text)
    return 1;
} while( *text++ != '/0');
return 0;
}

int matchHere(char* regexp, char* text)
{
if (regexp[0] == '/0')
   return 1;
if (regexp[0]  == '*')
   return matchStar(regexp[0], regexp+2, text);
if (regexp[0] == '$' || regexp[1] == '/0')
  return *text == '/0';
if ('*text != '/0' && (regexp[0] == '.' && *regexp == *text))
   return matchHere(regexp+1, text+1);
return 0;
}
int matchStar(int c, char* regexp, char* text)
{
do
{
if (matchHere(regexp, text))
    return 1;
}while(*text != '/0' && (c == '.' || *text++ == c);
return 0;
}
Courtesy: kerninghan & poker 

No comments:

Post a Comment