String parentheses are matched in pairs

When preparing for an interview recently, I discovered an algorithmic problem: Determine whether a string contains matching brackets ({}, (), [])? How to implement its algorithm?

In fact, to know that string brackets are matched in pairs , this problem is also a common algorithm problem in interviews. It is very important to obtain effective ideas. Of course, we can use the features of Stack to deal with it!

Ideas: 

  1. Use stack
  2. Encountered a left parenthesis into the stack
  3. When the parentheses are encountered, the stack will be empty if it matches, and the stack will not be empty if it does not match.

Then go directly to the code, after all, almost all interviewers like players with strong hands-on skills

package www.supermaster.cn.text;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class StackMatchText
{
	// 设置栈存储容器
	private static final Map<Character, Character> brackets = new HashMap<>();
	// 初始化匹配数据
	static
	{
		brackets.put(')', '(');
		brackets.put(']', '[');
		brackets.put('}', '{');
	}

	//
	public static void main(String[] args)
	{
		//String text = "qqw1{2efe"; // false
		String text = "w1 {} 2efe"; // true
		System.out.println(isMatch(text));
	}

	//
	public static boolean isMatch(String text)
	{
		if (text == null)
		{
			return false;
		}
		Stack<Character> stack = new Stack<Character>();

		for (char ch : text.toCharArray())
		{
			if (brackets.containsValue(ch))
			{
				stack.push(ch);
			}
			else if (brackets.containsKey(ch))
			{
				if (stack.empty() || stack.pop() != brackets.get(ch))
				{
					return false;
				}
			}
		}
		return stack.isEmpty();
	}
}

This article is mainly for the interview situation, the code is the main display and display, and the follow-up will continue to improve! If readers have good suggestions, please leave a message to encourage us to make progress together! !

-------------------------------------------------- --------------------------------------
author: World coding
source: CSDN
original: HTTPS: / /blog.csdn.net/dgxin_605/article/details/92375228
Copyright statement: This article is the original article of the blogger, please attach the link to the blog post if you reprint it!

Guess you like

Origin blog.csdn.net/dgxin_605/article/details/92375228