Find length of smallest window that contains all the characters of a string in another string

前端 未结 8 1506
不思量自难忘°
不思量自难忘° 2020-12-24 09:05

Recently i have been interviewed. I didn\'t do well cause i got stuck at the following question

suppose a sequence is given : A D C B D A B C D A C D and search seq

8条回答
  •  梦毁少年i
    2020-12-24 09:39

    Start from the beginning of the string.

    If you encounter an A, then mark the position and push it on a stack. After that, keep checking the characters sequentially until
    1. If you encounter an A, update the A's position to current value.
    2. If you encounter a C, push it onto the stack.

    After you encounter a C, again keep checking the characters sequentially until,
    1. If you encounter a D, erase the stack containing A and C and mark the score from A to D for this sub-sequence.
    2. If you encounter an A, then start another Stack and mark this position as well.
    2a. If now you encounter a C, then erase the earlier stacks and keep the most recent stack.
    2b. If you encounter a D, then erase the older stack and mark the score and check if it is less than the current best score.

    Keep doing this till you reach the end of the string.

    The pseudo code can be something like:

    Initialize stack = empty;
    Initialize bestLength = mainString.size() + 1; // a large value for the subsequence.
    Initialize currentLength = 0;
    for ( int i = 0; i < mainString.size(); i++ ) {
    
      if ( stack is empty ) {
        if ( mainString[i] == 'A' ) {
          start a new stack and push A on it.
          mark the startPosition for this stack as i.
        }
        continue;
      }
    
      For each of the stacks ( there can be at most two stacks prevailing, 
                               one of size 1 and other of size 0 ) {
        if ( stack size == 1 ) // only A in it {
          if ( mainString[i] == 'A' ) {
            update the startPosition for this stack as i.
          }
          if ( mainString[i] == 'C' ) {
            push C on to this stack.
          }
        } else if ( stack size == 2 ) // A & C in it {
          if ( mainString[i] == 'C' ) {
            if there is a stack with size 1, then delete this stack;// the other one dominates this stack.
          }
          if ( mainString[i] == 'D' ) {
            mark the score from startPosition till i and update bestLength accordingly.
            delete this stack.
          }
        }
    
      }
    
    }
    

提交回复
热议问题