1. 程式人生 > >LeetCode刷題——有效的括號

LeetCode刷題——有效的括號

大家好,今天繼續刷題日記,這道題是LeetCode裡面字串簡單難度的第三道題,但是卡了我非常多的時間。首先是題目要求:


下面介紹一下思路:

我最開始的想法非常複雜,設了三個指標,一個指向string的頭,一個指向string的尾,還有一個是變動指標,然後分段進行判斷迴圈,最後執行出來超時了。後來受到啟發,定義一個新的string,將原string的內容以棧的方式儲存進新的string中。每讀入一個新的字元就與前一個字元比較,看是否相差1或2。(()相差1,[]和{}相差2)如果相差1或2就看做配對成功,把最新讀入的和它前一個字元一起消掉,如果不匹配就入棧。直到整個string讀入完畢,看新定義的string是否為空,如果為空說明全部配對成功,返回true,如果還有殘餘的字元說明false。

下面上程式碼:

class Solution {
public:
    bool isValid(string s) {
	int j = 0;
	string temp;
	int len = s.size();
	temp += s[0];

	if (s[0] == '(' || s[0] == '[' || s[0] == '{'){
		for (int i = 1;i < len;i++){
			if ((s[i] == temp[j] + 1) || (s[i] == temp[j] + 2)){
				temp.erase (temp.end()-1);
				j--;
			}
			else {
				temp += s[i];
				j++;
			}
		}
		if (temp.empty())
			return true;
		else return false;
			
	}
	else{
	if (s  == "")
		return true;
	else return false;
	}
        
	}
};

下面做幾點說明,是我通過這道題學到的東西:

1.string可以通過+=的形式讀入字元,我以前都是以陣列下標的形式來處理的,最近新學到了折中方法,覺得很方便,也算是string的特性吧。

2.可以通過string.begin()和string.end()來查詢string的第一個和最後一個字元,注意string.end()是string最後一個字元的後一位,因此要查詢最後一個字元應該是string.end() - 1。我當時要查詢最後一位字元,百度到的很多方法都是讓我先length一下找到string的長度再通過下標讀取,我覺得這種方法很笨,像我這題中string是不斷讀入字元的,因此長度在變,那種方法就不適用了。

3.最開始include的string庫中包含很多好用的string函式,例如本題用到的erase,可以擦除指定位置的字元。

好了,我們下期見!

相關推薦

LeetCode——有效括號

大家好,今天繼續刷題日記,這道題是LeetCode裡面字串簡單難度的第三道題,但是卡了我非常多的時間。首先是題目要求:下面介紹一下思路:我最開始的想法非常複雜,設了三個指標,一個指向string的頭,一個指向string的尾,還有一個是變動指標,然後分段進行判斷迴圈,最後執行

LeetCode記錄_有效括號

leet 記錄 code lee 輸出 滿足 包括 val ack 題目: 給定一個只包括 ‘(‘,‘)‘,‘{‘,‘}‘,‘[‘,‘]‘ 的字符串,判斷字符串是否有效。 有效字符串需滿足: 左括號必須用相同類型的右括號閉合。 左括號必須以正確的順序閉合。 註意空字符

LeetCode記錄——第二十有效括號

20.有效的括號 題目描述 思路分析 程式碼實現 題目描述 給定一個只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字串,判斷字串是否有效。 有效字串需滿足: 左括號必須用相同型別的右括號閉合。 左括號必須以正確的

LeetCode筆記:有效括號

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid. An input st

LeetCode記錄4-有效括號

題目 由於只包含字元的字串’(‘,’)’,’{‘,’}’,’[‘和’]’,確定輸入字串是有效的。 括號必須關閉以正確的順序,”()”並且”()[]{}”都是有效的,但”(]”並”([)]”沒有效。 思路 首先我想改題目設計的括號種類肯定是可變的,但是

Leetcode筆記python---有效的字母異位詞

有效的字母異位詞 題目 給定兩個字串 s 和 t ,編寫一個函式來判斷 t 是否是 s 的一個字母異位詞。 示例 1: 輸入: s = “anagram”, t = “nagaram” 輸出: true 示例 2: 輸入: s = “rat”, t = “car

LeetCode記錄——第367有效的完全平方數)

題目描述 給定一個正整數 num,編寫一個函式,如果 num 是一個完全平方數,則返回 True,否則返回 False。 說明:不要使用任何內建的庫函式,如 sqrt。 示例 1: 輸入:16 輸出:True 示例 2: 輸入:14 輸出:F

leetcode 之路 68 Gas Station

rom 說明 之路 bsp margin tom otto mono lee There are N gas stations along a circular route, where the amount of gas at station i is gas[i]

LeetCode】SQL-Combine Two Tables

介紹 左關聯查詢 col 每一個 cit http sid combine sql查詢 Table: Person +-------------+---------+ | Column Name | Type | +-------------+---------+ |

[Leetcode] valid parentheses 有效括號

true class mine int min () etc strong bracket Given a string containing just the characters‘(‘,‘)‘,‘{‘,‘}‘,‘[‘and‘]‘, determine if the in

Leetcode總結: 445. Add Two Numbers II

num repr sum com single mes ans truct self You are given two non-empty linked lists representing two non-negative integers. The most sig

Leetcode記錄[python]——561 Array Partition I

partition span example ive 記錄 lan all [] result 一、前言 二、題561 Array Partition I Given an array of 2n integers, your task is to group the

Leetcode記錄[java]——485 Max Consecutive Ones

遍歷數組 刷題 color ati turn res positive pla str 一、前言 二、題485 Max Consecutive Ones Given a binary array, find the maximum number of consecut

Leetcode記錄[java]——695 Max Area of Island

思路 res because sum leetcode repr ava cte swe 一、前言 二、題695 Max Area of Island Given a non-empty 2D array grid of 0‘s and 1‘s, an island

leetcode總結(1)

solution 遍歷 AC 復雜度 刷題 may example AR 記錄 1、Two Sum Given an array of integers, return indices of the two numbers such that they add up to

leetcode 日誌 2018-03-26

運算 dir plan push tac and 註意 搜索 數字相加 58. 最後一個單詞的長度 分析:找最後一個非空格,向前找 int lengthOfLastWord(string s) { int i = s.find_l

leetcode之 字符串反轉

solution arr reverse eof HA rev code toc val 請編寫一個函數,其功能是將輸入的字符串反轉過來。 示例: 輸入:s = "hello" 返回:"olleh" 註:這裏之所以不使用倒敘遍歷strs,是因為字符串拼接的效率很低,str+

leetcode日記——反轉整數

leetcode給定一個 32 位有符號整數,將整數中的數字進行反轉。 這裏考慮,交換時,需要註意位數不同,需要乘上對應的位數,代碼如下: int reverse(int x) { int result = 0; while(x != 0) { int tmp = r

leetcode筆記231 2的冪

show 判斷 clas 進制 OS 分析 分享 bsp gif 題目描述: 給定一個整數,寫一個函數來判斷它是否是2的冪。 題目分析: 判斷一個整數是不是2的冪,可根據二進制來分析。2的冪如2,4,8,等有一個特點: 二進制數首位為1,其他位為0,如2為10

leetcode筆記342 4的冪

close body order 分析 pow 位操作 pre none click 題目描述: 給定一個整數 (32位有符整數型),請寫出一個函數來檢驗它是否是4的冪。 示例:當 num = 16 時 ,返回 true 。 當 num = 5時,返回 false。