纸上得来终觉浅, 绝知此事要躬行, 每天一道 CodeWar 编程题目
古人云: "纸上得来终觉浅 绝知此事要躬行."
编程是一门手艺活, 需要不断练习和实战才能学的好. PHP基础尤其重要, 要练习加深对PHP理解. 找了几个在线编程题库, 但都不支持PHP, 最后选中了CodeWar这个网站, 作为我练习PHP编程的.
打怪升级, 从此开始. 每天一道编程题目, 锻炼自己PHP能力, 顺便锻炼英文能力, 一举两得. 写完一道题目, 会分析自己思路和对比别人思路, 作成笔记加深印象. 比如有一道题目是用字母表数字替换字符串的字符 alphabet_position.题目如下:
In this kata you are required to, given a string, replace every letter with its position in the alphabet. If anything in the text isn't a letter, ignore it and don't return it. As an example:
alphabet_position('The sunset sets at twelve o\' clock.');
Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" as a string.
我的代码是这样子:
function alphabet_position(string $s): string
{
// 字母表数组
$letterArr = [1 => 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
// 将参数$s全部小写, 转换为目标数组
$targetArr = str_split(strtolower($s));
$result = '';
// 循环目标数组
foreach ($targetArr as $value) {
// 循环字母表数组
foreach ($letterArr as $k=>$v) {
// 比较两个数组中值,若相等, 取出字母表数组中键
if ($value == $v) {
$result .= $k.' ';
}
}
}
// 去除右边空格.
return rtrim($result);
}
我的思路: 用26个字母数组去对比参数数组, 符合则返回字母数组的键. 而别人思路让我学习一些知识和PHP用法.
function alphabet_position_clever(string $s): string
{
$value = '';
// 根据正则表达式排除非字符的字符串, 转换为目标数组, 并循环
foreach(str_split(preg_replace('/[^a-z]/i', '', $s)) as $letter) {
// 求每个大写英文字符 ASCII 码值.
// A在ASCII表是第65,依次排序25个字母,所以要减去64得到26个字母表正确数字
$letterToNumber = ord(strtoupper($letter)) - 64;
// 拼接字符串
$value .= " {$letterToNumber}";
}
return trim($value);
}
因此练习代码和看别人代码可以帮助自己提高编程能力. 若有新的思路, 欢迎留言或者在我的github项目留言.
每天都会在github提交一道题目,积少成多. 也欢迎能提供新的看法或者思路让我学习.万分谢谢.
文笔不好, 请多见谅.
本作品采用《CC 协议》,转载必须注明作者和本文链接
看了下 好像还不错的样子
使用哈希表 , O(n) , a=>1 b=>2 .............