Matching left and right brackets

        Given a string that only includes'(',')','{','}','[',']', judge whether the string is valid.

        A valid string must satisfy: the
        left parenthesis must be closed with the same type of right parenthesis.
        The opening parenthesis must be closed in the correct order.
        Note that an empty string can be considered a valid string.

Example 1:
        Input: "()"
        Output: true

Example 2:
        Input: “()[]{}”
        Output: true

Example 3:
        Input: "(]"
        Output: false

Example 4:
        Input: "([)]"
        Output: false

Example 5:
        Input: "{[]}"
        Output: true

        1. Solution: Put the string into the stack, all the left brackets are in the station, the marker cnt is added 1, and then all the left brackets matching the current right bracket are popped out of the stack, and the marker cnt is reduced by one; After completion, judge whether cnt is zero, if cnt=0, the parentheses are matched, otherwise they are not matched.
        The core code is as follows:
        //DoValid.cpp

bool DoValid(string& str) {
    
    
	string tmp;
	int cnt = 0;
	for (int i = 0; i < str.size(); i++) {
    
    
		if (str[i] == '{' || str[i] == '[' || str[i] == '(') {
    
    
			tmp.push_back(str[i]);
			cnt++;
		}
		else if (cnt != 0 && (tmp[cnt - 1] + 1 == str[i] || tmp[cnt - 1] + 2 == str[i])) {
    
    
			tmp.pop_back();
			cnt--;
		}
		else
			return false;
	}

	if (cnt != 0)
		return false;
	else
		return true;
}


class Solution {
    
    
public:
	bool isValid(string s) {
    
    
		return DoValid(s);
	}
};

        2.
        Source of remarks : LeetCode Question Number: 20
        Link: LeetCode Effective Bracket No20

Guess you like

Origin blog.csdn.net/sanqima/article/details/106868671