C++,codewars,Directions Reduction,550f22f4d758534c1100025a

/*
codewars,Directions Reduction,550f22f4d758534c1100025a
给定一个数组,数组中的元素是方向,例如["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"],
相邻的两个元素若方向相反可以抵消,例如"NORTH"和"SOUTH"可以抵消,"EAST"和"WEST"可以抵消,
最终返回一个数组,数组中的相邻元素均不能抵消例如["WEST"]。
*/

#include <vector>
#include <string>
#include <map>
class DirReduction
{
public:
    //static: 类中声明的静态成员变量或静态成员函属于类本身, 而不属于类的某个对象
    //静态成员变量在所有对象之间是共享的,
    //静态成员函数可以在没有对象实例的情况下调用
    static std::vector<std::string> dirReduc(std::vector<std::string> &arr){
        const std::map<std::string, std::string> opposite = {{"NORTH", "SOUTH"}, {"SOUTH", "NORTH"}, {"EAST", "WEST"}, {"WEST", "EAST"}};
        std::vector<std::string> result;
        for(auto& direction : arr){
            // if(result.empty() || result.back() != opposite[direction]){
            // std::map的 operator[]不适用于const对象, 因为 operator[]可能会插入新元素, 而const对象不允许修改
            // 使用const声明一个常量对象, 该对象的成员变量不能被修改, 并且只能调用const成员函数
            // 常量对象只能调用常量成员函数, 常量成员函数(const成员函数)不能修改对象的成员变量
            if(result.empty() || result.back()!=opposite.at(direction)){
                result.push_back(direction);
            }else{
                result.pop_back();
            }
        }
        return result;
    }
};
posted @ 2025-03-02 19:11  Kazuma_124  阅读(8)  评论(0)    收藏  举报