Created
March 23, 2018 19:17
-
-
Save JesseRhoads/5c14bba78a3e75a7e2e3997e13204615 to your computer and use it in GitHub Desktop.
Function to check if a string is a palindrome
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Palindrome | |
recognizes palindromes composed of unicode characters. | |
*/ | |
package palindrome | |
import "unicode/utf8" | |
func IsPalindrome(s string) bool { | |
// implementation here | |
if Reverse(s) == s { | |
return true | |
} else { | |
return false | |
} | |
} | |
// Super Fast UTF-8 compatible string reverse function from | |
// https://stackoverflow.com/questions/1752414/how-to-reverse-a-string-in-go/20225618#20225618 | |
func Reverse(s string) string { | |
size := len(s) | |
buf := make([]byte, size) | |
for start := 0; start < size; { | |
r, n := utf8.DecodeRuneInString(s[start:]) | |
start += n | |
utf8.EncodeRune(buf[size-start:], r) | |
} | |
return string(buf) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package palindrome | |
import "testing" | |
func TestPal(t *testing.T) { | |
checkTrue(IsPalindrome("ABBA"), t) | |
checkTrue(IsPalindrome("X"), t) | |
checkTrue(IsPalindrome("소있고지게지고있소"), t) | |
checkTrue(IsPalindrome("いかにもにかい"), t) | |
checkTrue(IsPalindrome("ANNA"), t) | |
checkTrue(IsPalindrome("RACECAR"), t) | |
checkFalse(IsPalindrome("Jesse"), t) | |
checkFalse(IsPalindrome("いかに"), t) | |
checkTrue(IsPalindrome("いかい"), t) | |
} | |
func checkTrue(b bool, t *testing.T) { | |
if b { | |
return | |
} else { | |
t.Error("Expected true, got false") | |
} | |
} | |
func checkFalse(b bool, t *testing.T) { | |
if !b { | |
return | |
} else { | |
t.Error("Expected false, got true") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment