classSolution { public: intminDistance(string word1, string word2){ int m = word1.size(); int n = word2.size(); vector<vector<int>> dp(m + 1, vector<int>(n + 1)); for (int i = 0; i <= m; ++i) dp[i][0] = i; for (int i = 0; i <= n; ++i) dp[0][i] = i; for (int i = 1; i <= m; ++i) for (int j = 1; j <= n; ++j) { int add = dp[i - 1][j] + 1; int del = dp[i][j - 1] + 1; int tak = dp[i - 1][j -1]; if (word1[i - 1] != word2[j - 1]) ++tak; dp[i][j] = min(add, min(del, tak)); } return dp[m][n]; } };
classSolution { public: intlongestValidParentheses(string s){ int len = s.size(); stack<int> stk; int result = 0; stk.push(-1); for (int i = 0; i < len; ++i) if (s[i] == '(') stk.push(i); else { stk.pop(); if (stk.empty()) stk.push(i); // 保证有数据作为未匹配字符 else result = max(result, i - stk.top()); } return result; } };
classSolution { public: intlongestValidParentheses(string s){ int len = s.size(); int result = 0; int left = 0, right = 0; for (int i = 0; i < len; ++i) // 无法处理左括号过多的情况 { if (s[i] == '(') ++left; else ++right; if (left == right) result = max(result, 2 * left); if (right > left) left = right = 0; // 不合法,重置 } left = right = 0; for (int i = len - 1; i >= 0; --i) // 无法处理右括号过多的情况 { if (s[i] == '(') ++left; else ++right; if (left == right) result = max(result, 2 * left); if (left > right) left = right = 0; // 不合法,重置 } return result; } };