Leetcode PHP题解--D37 682. Baseball Game

栏目: PHP · 发布时间: 6年前

内容简介:给定一个字符串数组,每一个字符串有以下形式:返回最终得分。

682. Baseball Game

题目链接

682. Baseball Game

题目分析

给定一个字符串数组,每一个字符串有以下形式:

+
D
C

返回最终得分。

思路

这题没什么好说的了。用switch...case区分各种情况,进行相应处理即可。

最终代码

<?php
class Solution {
    function calPoints($ops) {
        $points = [];
        foreach($ops as $op){
            $max = count($points);
            switch($op){
                case '+':
                    $p = 0;
                    if(isset($points[$max-1])){
                        $p += $points[$max-1];
                    }
                    if(isset($points[$max-2])){
                        $p += $points[$max-2];
                    }
                    $points[] = $p;
                    break;
                case 'D':
                    $points[] = isset($points[$max-1])?$points[$max-1]*2:0;
                    break;
                case 'C':
                    array_pop($points);
                    break;
                default:
                    $points[] = (int)$op;
                    break;
            }
        }
        return array_sum($points);
    }
}

若觉得本文章对你有用,欢迎用 爱发电 资助。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Data Structures and Algorithms

Data Structures and Algorithms

Alfred V. Aho、Jeffrey D. Ullman、John E. Hopcroft / Addison Wesley / 1983-1-11 / USD 74.20

The authors' treatment of data structures in Data Structures and Algorithms is unified by an informal notion of "abstract data types," allowing readers to compare different implementations of the same......一起来看看 《Data Structures and Algorithms》 这本书的介绍吧!

html转js在线工具
html转js在线工具

html转js在线工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具