Блог пользователя RNR

Автор RNR, история, 5 лет назад, По-английски

How to solve a generalization of this problem?

Given a string, remove identical consecutive letters ( not only pair as mentioned in the above question).

For example, if you have

wwwhaat --> ht
whhhaah --> w
reallazy --> rezy
whaahhhh --> w

Can someone suggest me an algorithm? For finding the minimum string at the end of this deletion?

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
5 лет назад, # |
  Проголосовать: нравится -6 Проголосовать: не нравится

Use stack and go backwards. If next element is equal to top of stack, pop top element and continue with next, otherwise, add that element to top of the stack.

  • »
    »
    5 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    How does this work? When the input is "wwwhaat" I think whatever you suggest outputs "wht". Can you check this?

    • »
      »
      »
      5 лет назад, # ^ |
        Проголосовать: нравится -6 Проголосовать: не нравится

      Well yes, but then if you have this case when next character is equal to top of the stack, iterate until you have character that is not equal to top of the stack and then pop it.

»
5 лет назад, # |
Rev. 4   Проголосовать: нравится 0 Проголосовать: не нравится

if we have baabba, what should be result? ba or a? That's the problem when you generalize this problem :) In both cases though, you should do a simulation with a linkedlist so erasing an element is constant time. If the answer is a, it can be done in O(N), as after each block deletion, you can check if previous character is equal to next, otherwise you have to do simulations from beginning until there is no deletion.