LeetCode刷题 Day11

74 阅读1分钟

LeetCode刷题 Day11

20. Valid Parentheses

Given a string s containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. Every close bracket has a corresponding open bracket of the same type.

  Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "()[]{}"
Output: true

Example 3:

Input: s = "(]"
Output: false

思路:

  • 用栈来保存左括号,当出现右括号的时候,将左括号出栈看是否匹配
  • 最后要检查stack.length === 0

代码:

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    let stack = [];
    let i = 0;
    let c = '';
    let topItem = '';
    
    while (i < s.length) {
        c = s[i];
        
        if (c === '[' || c === '{' || c === '(') {
            stack.push(c);
        } else {
            topItem = stack.pop();
            if ((c === ']' && topItem !== '[' ) ||
               (c === '}' && topItem !== '{' ) ||
               (c === ')' && topItem !== '(' )) {
                return false;
            }
        }
        i++;
    }
    
    return stack.length === 0;
};

时间复杂度: O(n) 空间复杂度: O(n)


1047. Remove All Adjacent Duplicates In String

You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.

We repeatedly make duplicate removals on s until we no longer can.

Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.

Example 1:

Input: s = "abbaca"
Output: "ca"
Explanation: 
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move.  The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".

Example 2:

Input: s = "azxxzy"
Output: "ay"

思路:

  • 对比s[i]和stack.peek()的值,如果相同就stack.pop()

代码:

/**
 * @param {string} s
 * @return {string}
 */
var removeDuplicates = function(s) {
    let stack = [];
    
    for (let i = 0; i < s.length; i++) {
        if (s[i] === stack[stack.length - 1]) stack.pop();
        else stack.push(s[i]);
    }
    
    return stack.join('');
};

时间复杂度: O(n) 空间复杂度: O(n)


150. Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +-*, and /. Each operand may be an integer or another expression.

Note that division between two integers should truncate toward zero.

It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation.

 

Example 1:

Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9

Example 2:

Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6

Example 3:

Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 22
Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

Constraints:

  • 1 <= tokens.length <= 104
  • tokens[i] is either an operator: "+""-""*", or "/", or an integer in the range [-200, 200].

思路:

  • 当tokens[i]在[-200, 200]之间时,说明为有效数字,直接push进stack
  • 当tokens[i]不在[-200, 200]之间时,执行两次pop操作 获取最近进栈的两个num,根据运算符号进行计算
  • 在算除法时,要注意正负值 负值为ceil,正值为floor

代码:

/**
 * @param {string[]} tokens
 * @return {number}
 */
var evalRPN = function(tokens) {
    let i = 0;
    let tokensLen = tokens.length;
    let stack = [];
    let num1 = 0;
    let num2 = 0;
    
    while (i < tokensLen) {
        let c = tokens[i];
        
        if (Number(c) <= 200 || Number(c) >= -200) {
            stack.push(Number(tokens[i]));
        } else {
            num1 = stack.pop();
            num2 = stack.pop();
            
            if (c === '+') {
                stack.push(num1 + num2);
            } else if (c === '-') {
                stack.push(num2 - num1);
            } else if (c === '*') {
                stack.push(num1 * num2);
            } else {
                let tempNum = num1 * num2 < 0 ? Math.ceil(num2 / num1) : Math.floor(num2 / num1)
                stack.push(tempNum);
            }
        }
         
        i++;
    }
    
    return stack.pop();
};

时间复杂度: O(n) 空间复杂度: O(n)