Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- object Balanced {
- def main(args: Array[String]) {
- val s1: String = "((a))"
- val s2: String = "a - )())()x("
- println(balanced(s1.toList))
- println(balanced(s2.toList))
- }
- def balanced (s: List[Char]): Boolean ={
- def countChar(l: List[Char], count: Int, s: Char): Int = {
- if (l.isEmpty) count
- else {
- if (s == l.head) countChar(l.tail, count + 1, s)
- else countChar(l.tail, count, s)
- }
- }
- def check (s: List[Char], c: Int): Boolean= {
- if (s.isEmpty && c == 0) true
- else if( s.isEmpty && c != 0) false
- else if(s.head == '(') check(s.tail, c +1)
- else if (s.head == ')' && c >0) check(s.tail, c -1)
- else check(s.tail, c)
- }
- if (countChar(s, 0, '(') == countChar(s, 0, ')')) check(s, 0)
- else false
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement