811. Subdomain Visit Count
: medium
Веб-сайт с доменом "
discuss.leetcode.com
" состоит из различных поддоменов. На верхнем уровне у нас есть "com", на следующем уровне - "
leetcode.com
", и на самом нижнем уровне - "
discuss.leetcode.com
". Когда мы посещаем домен, такой как "
discuss.leetcode.com
", мы также автоматически посещаем родительские домены "
leetcode.com
" и "com".
Домен с парным счетчиком - это домен, который имеет один из двух форматов "rep d1.d2.d3" или "rep d1.d2", где rep - это количество посещений домена, а d1.d2.d3 - это сам домен.
На예제, "9001
discuss.leetcode.com
" - это домен с парным счетчиком, указывающий на то, что
discuss.leetcode.com
был посещен 9001 раз.
Дан 배열 доменов с парными счетчиками cpdomains, return 배열 доменов с парными счетчиками для каждого поддомена во 입력ных данных. Вы можете вернуть ответ в любом порядке.
예제:
Input: cpdomains = ["9001 discuss.leetcode.com"]
Output: ["9001 leetcode.com","9001 discuss.leetcode.com","9001 com"]
Explanation: We only have one website domain: "discuss.leetcode.com".
As discussed above, the subdomain "leetcode.com" and "com" will also be visited. So they will all be visited 9001 times.
C# 해법
매칭됨/원본using System;
using System.Collections.Generic;
public class Solution {
public IList<string> SubdomainVisits(string[] cpdomains) {
var ans = new Dictionary<string, int>();
foreach (var domain in cpdomains) {
var parts = domain.Split(new char[] { ' ' });
var count = int.Parse(parts[0]);
var frags = parts[1].Split(new char[] { '.' });
for (int i = 0; i < frags.Length; i++) {
var subdomain = string.Join(".", frags, i, frags.Length - i);
if (ans.ContainsKey(subdomain)) {
ans[subdomain] += count;
} else {
ans[subdomain] = count;
}
}
}
var res = new List<string>();
foreach (var entry in ans) {
res.Add($"{entry.Value} {entry.Key}");
}
return res;
}
}
C++ 해법
자동 초안, 제출 전 검토#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public vector<string> SubdomainVisits(vector<string> cpdomains) {
var ans = new unordered_map<string, int>();
foreach (var domain in cpdomains) {
var parts = domain.Split(new char[] { ' ' });
var count = int.Parse(parts[0]);
var frags = parts[1].Split(new char[] { '.' });
for (int i = 0; i < frags.size(); i++) {
var subdomain = string.Join(".", frags, i, frags.size() - i);
if (ans.count(subdomain)) {
ans[subdomain] += count;
} else {
ans[subdomain] = count;
}
}
}
var res = new List<string>();
foreach (var entry in ans) {
res.push_back($"{entry.Value} {entry.Key}");
}
return res;
}
}
Java 해법
매칭됨/원본import java.util.*;
class Solution {
public List<String> subdomainVisits(String[] cpdomains) {
Map<String, Integer> ans = new HashMap<>();
for (String domain : cpdomains) {
String[] parts = domain.split(" ");
int count = Integer.parseInt(parts[0]);
String[] frags = parts[1].split("\\.");
for (int i = 0; i < frags.length; i++) {
String subdomain = String.join(".", Arrays.copyOfRange(frags, i, frags.length));
ans.put(subdomain, ans.getOrDefault(subdomain, 0) + count);
}
}
List<String> res = new ArrayList<>();
for (Map.Entry<String, Integer> entry : ans.entrySet()) {
res.add(entry.getValue() + " " + entry.getKey());
}
return res;
}
Python 해법
매칭됨/원본from collections import Counter
class Solution:
def subdomainVisits(self, cpdomains):
ans = Counter()
for domain in cpdomains:
count, domain = domain.split()
count = int(count)
frags = domain.split('.')
for i in range(len(frags)):
ans[".".join(fr
Go 해법
매칭됨/원본package main
import (
"strconv"
"strings"
)
func subdomainVisits(cpdomains []string) []string {
ans := make(map[string]int)
for _, domain := range cpdomains {
parts := strings.Split(domain, " ")
count, _ := strconv.Atoi(parts[0])
frags := strings.Split(parts[1], ".")
for i := range frags {
subdomain := strings.Join(frags[i:], ".")
ans[subdomain] += count
}
}
res := make([]string, 0, len(ans))
for dom, ct := range ans {
res = append(res, strconv.Itoa(ct)+" "+dom)
}
return res
}
Algorithm
Следуем указаниям из условия задачи.
Для адреса вида a.b.c, подсчитываем a.b.c, b.c и c. Для адреса вида x.y, подсчитываем x.y и y.
Для подсчета этих строк используем хеш-таблицу. Для разделения строк на требуемые части используем библиотечные функции split.
😎
Vacancies for this task
활성 채용 with overlapping task tags are 표시됨.