Ejemplo n.º 1
0
static int GFG_LongestSubstringParen( char* string, int length )
{
	Stack<int> subStringIndices;
	int result = 0;
	subStringIndices.Enqueue(-1);
	for(int i = 0; i < length; i++)
	{
		if( string[i] == '(' )
		{
			subStringIndices.Enqueue(i);
		}
		else if( string[i] == ')' )
		{
			delete subStringIndices.Dequeue();
			if( !subStringIndices.IsEmpty() )
			{
				int newLength = i - subStringIndices.Peek()->data;
				if( result < newLength) result = newLength;
			}
			else
			{
				subStringIndices.Enqueue(i);
			}
		}
	}
	return result;
}
Ejemplo n.º 2
0
static bool GFG_IsBST_GivenPreOrderTraversal( int* array, int n )
{
	Stack<int> parents;
	int prevMin;
	bool prevMinInitialised = false;
	//Continue pushing parents onto the stack until we discover a right subtree
	//If a right subtree is discovered, pop all the left nodes off the stack onto the array until the stack is empty or we find a parent of the right subtree
	for(int i = 0; i < n; i++)
	{
		if( parents.IsEmpty() || parents.Peek()->data > array[i] )
		{
			parents.Enqueue(array[i]);
		}
		else //right subtree discovered
		{
			while( !parents.IsEmpty() && parents.Peek()->data < array[i] )
			{
				int Value = parents.Dequeue()->data;
				//Test to see that the resulting array is sorted
				if( prevMinInitialised && prevMin > Value )
				{
					return false;
				}
				prevMinInitialised = true;
				prevMin = Value;
			}
			parents.Enqueue(array[i]);
		}
	}
	//Put all of the remaining parents into our array
	while( !parents.IsEmpty() ) { 
		int Value = parents.Dequeue()->data;
		//Test to see that the resulting array is sorted
		if( prevMinInitialised && prevMin > Value )
		{
			return false;
		}
		prevMinInitialised = true;
		prevMin = Value;
	}
	
	return true;
}