MAC地址合法性

solve actually problem!

给定一个字符串,按照下面规则返回所有合法的mac地址的数量:

  • 合法 mac 地址以字符串表示,由12位十六进制字符组成,每两个字符之间用 - 或 : 分隔
  • 合法的十六进制字符包含0-9,a-f,A-F,同一个 mac 中出现的字母可以大小写混用,不区分大小写
  • 一个mac地址中,不得混用 - 和 :
  • 相同mac地址需去重,注意,仅大小写,分隔符不同的两个 mac 地址字符串视为相同,如 aa-bb-12-cc-dd-ee与Aa:bB:12:CC:dd:ee视为相同。

非法mac地址如下:

aa-bb-2-cc-dd-ee-13

aa-bb-22-cc-dd-eG-41

aa-bb-22-988776766-23-12

代码实现如下:

#include <bits/stdc++.h>
using namespace std;
constexpr int MAX_LEN = 17;
class Solution {
public:
    bool IsValidMacAddr(const string &str)
    {
        string s = str;
        int cnt = 0;
        if (s.find(':') != string::npos && s.find('-') != string::npos) {
            return false;
        }

        for (int i = 0; i < s.size(); i++) {
            if (isdigit(s[i]) || (s[i] >= 'a' && s[i] <= 'f')) {
                cnt++;
                if (cnt > 2) {
                    return false;
                }
            } else if (s[i] == ':' || s[i] == '-') {
                s[i] = (s[i] == ':') ? '-' : s[i];
                if (i == 0 || cnt < 2) {
                    return false;
                }
                cnt = 0;
            } else {
                return false;
            }
        }
        return true;
    }
    
    int ParseMacNum(const string &inputStr)
    {
        if (inputStr.size() < MAX_LEN) {
            return 0;
        }
        unordered_set<string> set_;
        auto tempStr = inputStr;
        transform(tempStr.begin(), tempStr.end(), tempStr.begin(), ::tolower);
        for (int i = 0; i <= tempStr.size() - MAX_LEN; i++) {
            auto subStr = tempStr.substr(i, MAX_LEN);
            if (IsValidMacAddr(subStr)) {
                string s = subStr;
                replace(s.begin(), s.end(), ':', '-');
                set_.emplace(s);
            }
        }
        return set_.size();
    }
};