前言
在刷题中学习语言.
2022/10/5
leetcode每日一题:
题目代号 811
问题描述:
子域名访问记数
输入输出示例
问题解析:
- 首先遍历获取字串
- 截取字串中的访问次数rep和域名
- 通过map函数对获取的域名访问数进行统计
- 重新将map中的数据转化为vector格式
实现代码:
官方题解
代码如下(官方题解):
class Solution { public: vector<string> subdomainVisits(vector<string>& cpdomains) { vector<string> ans; unordered_map<string, int> counts; //采用哈希表存储结构的map容器,不具备map容器的自动排序功能//本题中不要求排序,只进行记录即可,故选用unordered_map for (auto &&cpdomain : cpdomains) { int space = cpdomain.find(' ');//找到" "的索引 int count = stoi(cpdomain.substr(0, space)); //通过substr()函数复制返回 0->space 之间的子字符串 //通过stoi()将字符串转化为整数 string domain = cpdomain.substr(space + 1);//获取" "后的子字符串 counts[domain] += count;//记录访问次数 for (int i = 0; i < domain.size(); i++) { if (domain[i] == '.') {//遍历"."获取子域名,父域名 string subdomain = domain.substr(i + 1); counts[subdomain] += count; } } } for (auto &&[subdomain, count] : counts) { ans.emplace_back(to_string(count) + " " + subdomain); } return ans; } }; 作者:LeetCode-Solution 链接:https://leetcode.cn/problems/subdomain-visit-count/solution/zi-yu-ming-fang-wen-ji-shu-by-leetcode-s-0a6i/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 ```
我的题解
class Solution {
public:
vector<string> subdomainVisits(vector<string>& cpdomains) {
map<string,int> m;
for(auto s:cpdomains){
stringstream out(s);//使用stringstream流进行数字转换
int n;
string s1;
out>>n>>s1;
m[s1]+=n;
for(int i=0;i<s1.size();i++){
if(s1[i]=='.'){
m[s1.substr(i+1)]+=n;
}
}
}
vector<string> res;
for(auto it:m)
res.push_back(to_string(it.second)+" "+it.first);
return res;
}
};
测试
参考文档:
总结
get到了新的容器和方法,开心😎