Last active
February 4, 2018 19:47
-
-
Save KristofferK/b6b5941f16d8669baec765940311c1b8 to your computer and use it in GitHub Desktop.
Checks if a string is a permutation of a palindrome. Solution-idea from https://medium.com/algorithms-practice/given-a-string-check-if-it-is-a-permutation-of-a-palindrome-e0469f47761d
This file contains hidden or 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
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using System.Text; | |
| using System.Threading.Tasks; | |
| namespace PermutationOfPalindrome | |
| { | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| IPermutationPalindromeChecker checker = new PermutationPalindromeCheckerImpl(); | |
| PrintCheckerResult(checker, "ned den laks skal"); // True (den laks skal ned) | |
| PrintCheckerResult(checker, "ned den laks Skal"); // False (because of capitalized S) | |
| PrintCheckerResult(checker, "1122443553"); // True (1234554321) | |
| PrintCheckerResult(checker, "112244353"); // True (123454321) | |
| PrintCheckerResult(checker, "Hej"); // False | |
| } | |
| private static void PrintCheckerResult(IPermutationPalindromeChecker checker, string s) | |
| { | |
| Console.WriteLine(s + " " + checker.IsPermutationOfPalindrome(s)); | |
| } | |
| } | |
| interface IPermutationPalindromeChecker | |
| { | |
| bool IsPermutationOfPalindrome(string s); | |
| } | |
| class PermutationPalindromeCheckerImpl : IPermutationPalindromeChecker | |
| { | |
| private static Dictionary<char, int> charsUsed; | |
| public bool IsPermutationOfPalindrome(string s) | |
| { | |
| charsUsed = new Dictionary<char, int>(); | |
| foreach (var c in s) | |
| { | |
| charsUsed[c] = charsUsed.ContainsKey(c) ? charsUsed[c] + 1 : 1; | |
| } | |
| return charsUsed.Where(e => e.Value % 2 != 0).Count() <= 1; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment