Thursday, September 14, 2017

Codility - Lesson 7 Stacks and Queues - 1. Brackets

Source Link:
https://codility.com/programmers/lessons/7-stacks_and_queues/brackets/

Question: 
A string S consisting of N characters is considered to be properly nested if any of the following conditions is true:
  • S is empty;
  • S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string;
  • S has the form "VW" where V and W are properly nested strings.
For example, the string "{[()()]}" is properly nested but "([)()]" is not.
Write a function:

class Solution { public int solution(String S); }

that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise.

For example, given S = "{[()()]}", the function should return 1 and given S = "([)()]", the function should return 0, as explained above.
Assume that:
  • N is an integer within the range [0..200,000];
  • string S consists only of the following characters: "(", "{", "[", "]", "}" and/or ")".
Complexity:
  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(N) (not counting the storage required for input arguments).

My Solution:
Notes:
1. main idea: use "Stack" (push and pop)
2. new Stack<Character>()
Stack<Character> stack = new Stack<>();
3. scan the string (just one pass)
for(int i=0; i< S.length(); i++){ 
// note: push "its pair"
if( S.charAt(i) == '(' ){
stack.push(')');
}
...
// pop and check
else if( S.charAt(i) == ')' || S.charAt(i) == ']' || S.charAt(i) == '}'){
// important: check if the stack is empty or not (be careful)
if(stack.isEmpty() == true){
return 0;
}
else{
char temp = stack.pop(); // check if the stack is empty before pop!!!
if(temp != S.charAt(i)){ // not a pair
return 0;
}
}
}
    
4. check if the stack is empty or not (be careful)
if( !stack.isEmpty() ){
return 0;
}
else{
return 1;

1 comment:

Codility - Lesson 16 Greedy algorithms - 2. MaxNonoverlappingSegments

Source Link: https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ Question: Located on a line ...