Skip to content

Commit a333b07

Browse files
committed
August Day 3
1 parent 96e5e40 commit a333b07

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.leetcode.scala.monthly2020.august
2+
3+
/*
4+
* Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
5+
*
6+
* Note: For the purpose of this problem, we define empty string as valid palindrome.
7+
*
8+
* */
9+
10+
/*
11+
* Input: "A man, a plan, a canal: Panama"
12+
Output: true
13+
*
14+
* Input: "race a car"
15+
Output: false
16+
*
17+
* Constraints:
18+
* s consists only of printable ASCII characters.
19+
*
20+
* */
21+
22+
/*
23+
* Approach: Iterative
24+
* 1. Iterate through each character and form the string alphaNumeric character.
25+
* 2. Compare the new string value with reverse value of new string.
26+
*
27+
* */
28+
29+
30+
object ValidPalindrome {
31+
def main(args: Array[String]): Unit = {
32+
val s1 = "A man, a plan, a canal: Panama"
33+
val s2 = "race a car"
34+
val s3 = "0p"
35+
val testCases = Array(s1, s2, s3)
36+
val expectedResults = Array(true, false, false)
37+
val actualResults = testCases.map(isPalindrome)
38+
println(s"Results: ${actualResults.mkString(" ")}, ${actualResults.sameElements(expectedResults)}")
39+
}
40+
41+
def isPalindrome(s: String): Boolean = {
42+
var string: StringBuilder = new StringBuilder()
43+
for (char <- s) {
44+
if ((char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || (char >= '0' && char <= '9')) {
45+
string = string.append(char.toLower)
46+
}
47+
}
48+
return string.equals(string.reverse)
49+
}
50+
}

0 commit comments

Comments
 (0)