- Last Stone Weight3
- Remove All Adjacent Duplicates In String4
- Longest String Chain6
- Last Stone Weight II
1. Last Stone Weight3
a collection of rocks with each one has positive weight. Each turn, we choose two heaviest rocks and smash them together.
logic:
sort them in increase order, and push back the last two elements, and smash and push the remain back to the vector.
solution:
1 | public: |
2. Remove All Adjacent Duplicates In String4
Given a String S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.
Repeatly doing the removement until we no longer can. return the final string.
example: inputs: “abbaca”
outputs: “ca”
Solution Logic: using stack, check the top of the stack, if equal to current element, then pop it out.
1 | public: |
3. Longest String Chain6
Given a list of words, each word consists of English lowercase letters.
Let’s say word1 is a predecessor of word2 if and only if we can add exactly one letter anywhere in word1 to make it equal to word2. For example, “abc” is a predecessor of “abac”.
Return the longest possible length of a word chain with words chosen from the given list of words.
Example 1:
1 | Input: ["a","b","ba","bca","bda","bdca"] |
Solution:
Per inolving in state transfer: Dynamic programming is needed.
sort the word based on the length; then loop through all the possible string by missing one letter. if one string got seen before, we update the longest chain for current string.
1 | class solution{ |
4. Last Stone Weight II
Follow up of the first one: not the biggest two stones anymore, but the smash strategy become:
1 | Each turn, we choose any two rocks and smash them together. |
So, there are a lot of choices! ===> Knapsacks problem!
###Tips: Think in the way of real scenarios, and how you get it done first.
Then connect the logic with data structure and algorithm.