Skip to content

Commit 1d4f42e

Browse files
Merge pull request #19 from alessandron3/master
Added Palindrome algorithm
2 parents 16dbd28 + a8bbbfd commit 1d4f42e

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

src/main/kotlin/other/Palindrome.kt

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package other
2+
3+
import java.text.Normalizer
4+
import java.util.regex.Pattern
5+
6+
/**
7+
* A palindrome is a word, number, phrase, or other sequence
8+
* of characters which reads the same backward as forward,
9+
* such as madam, racecar. There are also numeric palindromes,
10+
* particularly date/time stamps using short digits 11/11/11 11:11
11+
* and long digits 02/02/2020
12+
*
13+
* This function
14+
* @param text The text to be checked if it is a palindrome
15+
* @return return true if the text is a Palindrome
16+
*/
17+
fun isPalindrome(text: String): Boolean {
18+
19+
val normalizedText = text.normalize()
20+
for(i in normalizedText.indices)
21+
if(normalizedText[i] != normalizedText[normalizedText.length - (i + 1)])
22+
return false
23+
return true;
24+
}
25+
26+
27+
fun String.normalize(): String {
28+
val nfdNormalizedString = Normalizer.normalize(this, Normalizer.Form.NFD)
29+
return Pattern
30+
.compile("\\p{InCombiningDiacriticalMarks}+")
31+
.matcher(nfdNormalizedString)
32+
.replaceAll("")
33+
.toLowerCase()
34+
.replace(" ", "")
35+
36+
}
+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package other
2+
3+
import org.junit.Assert.assertTrue
4+
import org.junit.Test
5+
6+
class PalindromeTest {
7+
8+
@Test
9+
fun testPalindromePortuguesePhrase() {
10+
val text = "A mãe te ama"
11+
assertTrue(isPalindrome(text))
12+
}
13+
14+
@Test
15+
fun testPalindromeEnglishPhrase() {
16+
val text = "Mr Owl ate my metal worm"
17+
assertTrue(isPalindrome(text))
18+
}
19+
20+
@Test
21+
fun testPalindromeName() {
22+
val text = "Hannah"
23+
assertTrue(isPalindrome(text))
24+
}
25+
26+
@Test
27+
fun testPalindromeNumber() {
28+
val text = "2002"
29+
assertTrue(isPalindrome(text))
30+
}
31+
}

0 commit comments

Comments
 (0)