1. 程式人生 > >演算法設計與分析(14)-- Valid Parentheses(難度:Easy)

演算法設計與分析(14)-- Valid Parentheses(難度:Easy)

演算法設計與分析(14)

題目:Valid Parentheses

問題描述:Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

演算法思路:

問題為求括號的組合形式是否有效,注意這裡使用動態規劃並不是一個好的方法。因為當你需要把這個問題劃分為多個小問題的時候,你會遇到劃分的麻煩。例如,”(([]){})()”, 因為頭一個為”(“,找一個”)”作為劃分時會遇到問題。想要求解需要遍歷所有的劃分情況,這樣的效率是很低的。
這裡可以使用高效的演算法,因為每個有效的括號比為一對的,所以我們使用stack棧的方式。我們遍歷整個字串:
(1)當括號為”(“或”{“或”[“時,把其放入棧中。
(2)當括號為”)”或”}”或”]”時,若組合的形式是有效的,那麼棧中的top必然是對應的左括號,可以把對應的左括號push出來。若不是或者棧為空,那麼肯定是無效的。
(3)當已經遍歷完的整個字串,若棧為空,那麼該組合有效,否則無效。

實現程式碼:

#include<iostream>
#include<string>
#include<stack>
#include<map>

using namespace std;

bool isValid(string s) 
{
    stack<char> sta;
    map<char, char> cmap;
    cmap[')'] = '(';
    cmap[']'] = '[';
    cmap['}'] = '{';
    for (int i = 0; i < s.length(); ++i)
    {
        if
(s[i] == '(' || s[i] == '{' || s[i] == '[') sta.push(s[i]); else if (!sta.empty() && cmap[s[i]] == sta.top()) sta.pop(); else return false; } return sta.empty(); } int main() { string s = ")"; cout << isValid(s) << endl; return
0; }

相關推薦

演算法設計分析14-- Valid Parentheses難度Easy

演算法設計與分析(14) 題目:Valid Parentheses 問題描述:Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine

演算法設計分析——動態規劃矩陣連乘

動態規劃——Dynamic programming,可以說是本人一直沒有啃下的骨頭,這次我就得好好來學學Dynamic programming. OK,出發! 動態規劃通常是分治演算法的一種特殊情況,它一般用於最優化問題,如果這些問題能夠: 1.能夠分解為規模更小的子問題 2.遞迴的

演算法設計分析

53.Question Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum a

演算法設計分析:Divide And Conquer

Maximum Subarray Given an integer array nums, find the contiguous subarray (containing at least one number) which has the larges

演算法設計分析

53.Course Schedule There are a total of n courses you have to take, labeled from 0 to n-1. Some courses may have prerequisites, for

演算法設計分析——遞迴分治

目錄  D、走迷宮 提示: 提示:  NOJ 2018.9.21 A、二分查詢 時限:1000ms 記憶體限制:10000K  總時限:3000ms 描述 給定一個單調遞增的整數序列,問某個整數是否在序列中。 輸入

演算法設計分析第四周練習圖論

Network Delay Time 1. 題目 There are N network nodes, labelled 1 to N. Given times, a list of travel times as directed edges times[i

演算法設計分析K-Similar StringsWeek 5

學號:16340008 Question: Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A

演算法設計分析上週第五週的寫錯標題,這才是真正的第六週

Merge k Sorted Lists 題目 Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example:

演算法設計分析Burst BalloonsWeek 6

學號:16340008 Question: Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums.

演算法設計分析Graph And Tree

Couples Holding Hands N couples sit in 2N seats arranged in a row and want to hold hands. We want to know the minimum number of swa

《計算機演算法設計分析 第4版 (王曉東) 課後答案[1-9章]》pdf版電子書附下載連結+30個總結JVM虛擬機器的技術文排版好收藏版

技術書閱讀方法論 一.速讀一遍(最好在1~2天內完成) 人的大腦記憶力有限,在一天內快速看完一本書會在大腦裡留下深刻印象,對於之後複習以及總結都會有特別好的作用。 對於每一章的知識,先閱讀標題,弄懂大概講的是什麼主題,再去快速看一遍,不懂也沒有關係,但是一定要在不懂的

計算機演算法設計分析 貪心演算法--單源最短路徑

1.Dijkstra演算法是解決單源最短路徑的一個貪心演算法。給定一個帶權有向圖G=(V,E),其中每條邊的權都是非負實數,另外,還給定V中的一個頂點,稱為源。現在要計算源到其他各個頂點的最短路長度。這裡的路的長度指的是路上各邊權之和。 Dijkstra演算法可

演算法設計分析Scramble StringWeek 8

學號:16340008 Question: Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursive

演算法設計分析——二叉堆

本blog主要介紹了二叉堆、二項式堆,下一篇部落格將介紹斐波拉契堆。 二叉堆和二項式堆、斐波拉契堆都是用於實現優先佇列的高階資料結構,以不同堆實現的優先佇列會有不同的時間複雜度。 問題引入 在實際應用中,我們經常會遇到在最多由n個數組成的動態集合SSS上得到這個

8601 最大長方體問題優先做 時間限制:1000MS 記憶體限制:1000K 提交次數:950 通過次數:383 計算機演算法設計分析 王曉東

題目 8601 最大長方體問題(優先做) 時間限制:1000MS 記憶體限制:1000K 提交次數:950 通過次數:383 題型: 程式設計題 語言: G++;GCC;VC Description 一個長,寬,高分別是m,n,p的長方體被分割成mnp個小

演算法設計分析--動態規劃

Scramble String 題目 Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursive

演算法設計分析十一

300. Longest Increasing Subsequence Given an unsorted array of integers, find the length of longest increasing subsequence. Example

計算機演算法設計分析課本王曉東著課後演算法實現題1-3 最多約數問題

問題描述: 正整數x的約數是能整除x的正整數。正整數x的約數個數記為div(x)。例如,1 2 5 10都是10的約數,且div(10)=4。設a和b是2個正整數,a<=b,找出a和b之間約數個數最多的數x。 演算法設計: 對於給定的2個正整數a<=b,計算a和b之間約數個數最多

0x05演算法設計分析複習演算法設計策略-分治法2

參考書籍:演算法設計與分析——C++語言描述(第二版) 演算法設計策略-分治法 二分搜尋 問題描述 在有序表(已按關鍵字值非減排序)中搜索給定元素的問題。 分治法求解 設有一個長度為n的有序表(a0,a1,⋯,an−1),要求