Anagrams
HackerRank 问题: Anagrams
Question
Answer
PHP
<?php
function anagram($check_anagram_string) {
$check_string_length = strlen($check_anagram_string);
if ($check_string_length % 2 == 1) {
// is odd string, can not compare
return -1;
}
// convert to lower case
$check_anagram_string = strtolower($check_anagram_string);
// split string to different variable
$sub_string_index = (int) floor($check_string_length / 2);
$compare_string_1 = substr($check_anagram_string, 0, $sub_string_index);
$compare_string_2 = substr($check_anagram_string, -$sub_string_index);
$check_letter_mapping = [];
for ($check_sting_1_index = 0; $check_sting_1_index < $sub_string_index; $check_sting_1_index++) {
$letter = $compare_string_1[$check_sting_1_index];
if (!isset($check_letter_mapping[$letter])) {
// the letter never exist
$check_letter_mapping[$letter] = 1;
continue;
}
// add letter show times
$check_letter_mapping[$letter]++;
}
for ($check_sting_2_index = 0; $check_sting_2_index < $sub_string_index; $check_sting_2_index++) {
$letter = $compare_string_2[$check_sting_2_index];
if (!isset($check_letter_mapping[$letter])) {
// the letter never exist
$check_letter_mapping[$letter] = -1;
continue;
}
// letter already exist in string 1, delete compare times
$check_letter_mapping[$letter]--;
}
$change_to_anagram_change_times = 0;
foreach ($check_letter_mapping as $letter => $letter_compare_result) {
if ($letter_compare_result > 0) {
$change_to_anagram_change_times+=$letter_compare_result;
}
}
return $change_to_anagram_change_times;
}