1. 程式人生 > >演算法設計與分析第八週leetcode

演算法設計與分析第八週leetcode

  1. Longest Valid Parentheses

Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.

Example 1:

Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"

Example 2:

Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"

解答過程: 一開始思路是計算可以與’(‘匹配的’)'數量來計算結果,但是這樣算的答案不是不一定是字串的,例如"(()(()“用這個方法算出來的是4,將兩個”()“都計算了,但這兩個”()"並非連在一起的子字串,正確答案應該為2 下面是一開始的錯誤程式碼:

class Solution {
public:
	stack<int> STACK;//0代表左括號,1代表右括號
	int longestValidParentheses(string s) {
		int result=0;
		for (int i = 0; i < s.size(); i++) {
			if (s[i] == '(') {
				STACK.push(0);
			}
			else {
				if (STACK.size() != 0) {
					result += 2;
					STACK.pop();
				}
			}
		}
		return result;
	}
};

為了正確計運算元字串的長度,很明顯需要將無法匹配的括號位置單獨記錄下來,上面的例子"(()(()“就需要將第0和第3號位置的”("單獨記錄位置以標記這兩個端點。處理之後,兩個子字串範圍分別為[1 ~ 2] 和 [4 ~ 5] ,取子字串長度最長即為答案。 下面為最終程式碼:

class Solution {
public:
	stack<int> STACK;//輸入的數字代表對應的位置
	int longestValidParentheses(string s) {
		int result = 0;
		for (int i = 0; i < s.size(); i++) {
			if (STACK.size() != 0 && s[STACK.top()] == '('&&s[i]==')') {
				STACK.pop();
			}
			else {
				STACK.push(i);
			}
		}

		if (STACK.size() == 0) {
			result = s.size();

		}
		else {
			int stackSize = STACK.size(), back = 0, front = 0;
			result = s.size() - STACK.top() - 1;
			for (int i = 0; i < stackSize - 1; i++) {
				back = STACK.top();
				STACK.pop();
				front = STACK.top();
				result = max(back - front - 1, result);
			}
			result = max(STACK.top(), result);
		}
		return result;
	}
};