Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Valid Parenthesis #11

Closed
ralic opened this issue Sep 29, 2017 · 1 comment
Closed

Valid Parenthesis #11

ralic opened this issue Sep 29, 2017 · 1 comment

Comments

@ralic
Copy link

ralic commented Sep 29, 2017

The golang solution using byte to validate the parenthesis hits 0ms compared to ~108ms in javascript.
Maybe we shall try to find a better solution.

func isValid(s string) bool {
	if len(s)%2 != 0 {
		return false
	}
	left := map[byte]struct{}{
		'(': struct{}{},
		'[': struct{}{},
		'{': struct{}{},
	}
	right := map[byte]struct{}{
		')': struct{}{},
		']': struct{}{},
		'}': struct{}{},
	}
	bytes := []byte(s)
	stack := []byte{}
	for i := range bytes {
		if _, ok := left[bytes[i]]; ok {
			stack = append(stack, bytes[i])
		} else if _, ok = right[bytes[i]]; ok {
			if len(stack) == 0 {
				return false
			}
			switch stack[len(stack)-1] {
			case '(':
				if bytes[i] != ')' {
					return false
				}
			case '[':
				if bytes[i] != ']' {
					return false
				}
			case '{':
				if bytes[i] != '}' {
					return false
				}
			}
			stack = stack[:len(stack)-1]
		} else {
			return false
		}
	}
	if len(stack) == 0 {
		return true
	}
	return false
}
@lessfish
Copy link
Owner

lessfish commented Oct 8, 2017

if golang is quicker than JavaScript, it's okay
if having an better solution using JavaScript, PRs welcomed!

@lessfish lessfish closed this as completed Oct 8, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants