From f99770d17641160dca4d0ddc192f5f82fd2fc235 Mon Sep 17 00:00:00 2001 From: robinsonvs Date: Wed, 20 Oct 2021 23:00:40 -0300 Subject: [PATCH 1/2] add valid parenthesis solution in java --- .../valid-parenthesis.java | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 leetcode/20 - validparenthesis/valid-parenthesis.java diff --git a/leetcode/20 - validparenthesis/valid-parenthesis.java b/leetcode/20 - validparenthesis/valid-parenthesis.java new file mode 100644 index 0000000..50a2ee3 --- /dev/null +++ b/leetcode/20 - validparenthesis/valid-parenthesis.java @@ -0,0 +1,46 @@ +package Algoritms; + +import java.util.ArrayDeque; +import java.util.Deque; + +public class ValidParenthesis { + + public static void main(String[] args) { + + System.out.println(isValid("()[]{}")); // true + System.out.println(isValid("([)]")); // false + System.out.println(isValid("([{}])")); // true + } + + private static boolean isValid(String s) { + Deque stack = new ArrayDeque<>(); + + for (int i = 0; i < s.length(); i++) { + char item = s.charAt(i); + + if (item == '(' || item == '{' || item == '[') { + stack.push(item); + continue; + } + + if (stack.isEmpty()) { + return false; + } + + char valid = stack.pop(); + switch (item) { + case ')': + if (valid == '{' || valid == '[') return false; + break; + case '}': + if (valid == '(' || valid == '[') return false; + break; + case ']': + if (valid == '(' || valid == '{') return false; + break; + } + } + + return stack.isEmpty(); + } +} From 62b20f15b3a8c2e3bedc33a296d93832bebf3abc Mon Sep 17 00:00:00 2001 From: robinsonvs Date: Thu, 21 Oct 2021 02:15:51 -0300 Subject: [PATCH 2/2] add valid parenthesis solution in scala --- .../valid-parenthesis.scala | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 leetcode/20 - validparenthesis/valid-parenthesis.scala diff --git a/leetcode/20 - validparenthesis/valid-parenthesis.scala b/leetcode/20 - validparenthesis/valid-parenthesis.scala new file mode 100644 index 0000000..9e27e17 --- /dev/null +++ b/leetcode/20 - validparenthesis/valid-parenthesis.scala @@ -0,0 +1,24 @@ +package Algoritms + +object ValidParenthesis extends App { + + def validSequence(chr: Char, head: Char): Boolean = { + chr == ')' && head == '(' || chr == ']' && head == '[' || chr == '}' && head=='{' + } + + def isValid(s: String): Boolean = { + s.foldLeft(List[Char]()) ((accumulator, chr) => { + chr match { + case '(' | '{' | '[' => chr :: accumulator + case ')' | '}' | ']' => accumulator match { + case head :: tail => if (!validSequence(chr, head)) return false else tail + } + } + }).isEmpty + } + + println(isValid("()[]{}")) // true + println(isValid("([)]")) // false + println(isValid("([{}])")) // true + +}