Intern
func countSubs(s string) int { result := 0 left := 0 hm := make(map[rune]int) for right := 0; right < len(s); right++ { hm[s[right]]++ for hm[s[right]] > 1 { hm[s[left]]-- if hm[s[left]] == 0 { delete(hm, s[left]) } left++ } result += (right - left + 1) } return result }
sobes.tech AI
Answer from AI
The countSubs function counts the number of substrings in the string s where all characters are unique.
The algorithm uses the "sliding window" method with two pointers left and right. The dictionary hm stores the count of each character in the current window.
- When expanding the window to the right, increment the character count.
- If a character appears more than once, move the left pointer, decreasing counts until the repetition disappears.
- The number of unique substrings ending at position
rightequals the length of the current window(right - left + 1). - Sum this value for all positions.
Example usage:
total := countSubs("abc") // total = 6, substrings: "a", "b", "c", "ab", "bc", "abc"
Thus, the function efficiently counts the number of substrings without repeating characters in O(n).