Unique Letter String LT828

A character is unique in string S if it occurs exactly once in it.

For example, in string S = "LETTER", the only unique characters are "L" and "R".

Let‘s define UNIQ(S) as the number of unique characters in string S.

For example, UNIQ("LETTER") =  2.

Given a string S with only uppercases, calculate the sum of UNIQ(substring) over all non-empty substrings of S.

If there are two or more equal substrings at different positions in S, we consider them different.

Since the answer can be very large, return the answer modulo 10 ^ 9 + 7.

Idea 1. Dynamic programming, it‘s a bit tricky, need to store last two indexes for each char appears in the array, assume dp[i] is the number of unique characters ending at s[i]

dp[i] = dp[i-1] + (i - last[s[i]]) - (last[s[i]] - 2ndLast[s[i]]))

ABCBDAB

i = 0, {A}, dp[0] = 1

i = 1, {AB, B}, dp[1] = 3

i = 2, {ABC, BC, C}, dp[2] = 6

i = 3, {ABCB, BCB, CB, B}, dp[3] = 6 = dp[2] + (3 - 1) -(1 - (-1)) = 6

Time complexity: O(n)

Space complexity: O(n) or O(26)

 1 class Solution {
 2     public int uniqueLetterString(String S) {
 3         int[] last = new int[26];
 4         int[] secondLast = new int[26];
 5         Arrays.fill(last, -1);
 6         Arrays.fill(secondLast, -1);
 7
 8         int dp = 0;
 9         int result = 0;
10         for(int i = 0; i < S.length(); ++i) {
11             int a = S.charAt(i) - ‘A‘;
12             dp = dp + (i -last[a]) - (last[a] - secondLast[a]);
13             result += dp;
14             secondLast[a] = last[a];
15             last[a] = i;
16         }
17
18         return result;
19     }
20 }

Idea 2. Similar to Sum of Subsequence Widths LT891, instead of getting all the unique characters for substring ending at index i, focus on the contribution of each character, count how many times it appears as a unique character in a substring, then sum it up for each char in the string and get the result.

ABCBDAB, for the middle ‘B‘, on the left, substring ending at ‘B‘: B, CB

              on the right, substring starting at ‘B‘: B, BD, BDA

‘B‘ can appears 2 * 3 = 6 substring, B, BD, BDA, CB, CBD, CBDA,

It can observed that the count is depend on the nearest same char on the left and on the right,

  (i - prev) * (next - i)

Time complexity: O(n)

Space complexity: O(n)

Using hashmap to store the index of char in the string

 1 class Solution {
 2     public int uniqueLetterString(String S) {
 3         Map<Character, List<Integer>> charIndex = new HashMap<>();
 4         int n = S.length();
 5         for(int i = 0; i < n; ++i) {
 6             char c = S.charAt(i);
 7             if(!charIndex.containsKey(c)) {
 8                 charIndex.put(c, new ArrayList<Integer>());
 9             }
10             charIndex.get(c).add(i);
11         }
12
13         long result = 0;
14         long mod = (long)1e9+7;
15
16         for(List<Integer> positions: charIndex.values()) {
17
18             for(int i = 0; i < positions.size(); ++i) {
19                 int prev = i > 0? positions.get(i-1) : -1;
20                 int next = i < positions.size()-1? positions.get(i+1) : n;
21
22                 int curr = positions.get(i);
23                 result = (result + (curr-prev) * (next - curr))%mod;
24             }
25         }
26
27         return (int)result;
28     }
29 }

Idea 2.b store index at array prev[], next[] by scanning the string from left to right, and right to left

Time complexity: O(n)

Space complexity: O(n)

 1 class Solution {
 2     public int uniqueLetterString(String S) {
 3         int n = S.length();
 4         int[] charIndex = new int[26];
 5         Arrays.fill(charIndex, -1);
 6
 7         int[] prev = new int[n];
 8         for(int i = 0; i < n; ++i) {
 9             int a = S.charAt(i) - ‘A‘;
10             prev[i] = charIndex[a];
11             charIndex[a] = i;
12         }
13
14         Arrays.fill(charIndex, n);
15         int[] next = new int[n];
16         for(int i = n-1; i >= 0;--i) {
17             int a = S.charAt(i) - ‘A‘;
18             next[i] = charIndex[a];
19             charIndex[a] = i;
20         }
21
22         int result = 0;
23         int mod = (int)(1e9) + 7;
24
25         for(int i = 0; i < n; ++i) {
26             result = (result + (i - prev[i])*(next[i] - i))%mod;
27         }
28
29         return result;
30     }
31 }

Example 1:

Input: "ABC"
Output: 10
Explanation: All possible substrings are: "A","B","C","AB","BC" and "ABC".
Evey substring is composed with only unique letters.
Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10

Example 2:

Input: "ABA"
Output: 8
Explanation: The same as example 1, except uni("ABA") = 1.

原文地址:https://www.cnblogs.com/taste-it-own-it-love-it/p/10781583.html

时间: 2024-10-13 05:16:37

Unique Letter String LT828的相关文章

LeetCode题828 —— Unique Letter String

https://leetcode.com/problems/unique-letter-string/description/ A character is unique in string S if it occurs exactly once in it. For example, in string S = "LETTER", the only unique characters are "L" and "R". Let's define 

【LeetCode】双指针 two_pointers(共47题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [3]Longest Substring Without Repeating Characters [11]Container With Most Water [15]3Sum [16]3Sum Closest [18]4Sum [19]Remove Nth Node From End of List [26]Remove Duplicates from Sorted

【Leetcode周赛】从contest-81开始。(一般是10个contest写一篇文章)

Contest 81 (2018年11月8日,周四,凌晨) 链接:https://leetcode.com/contest/weekly-contest-81 比赛情况记录:结果:3/4, ranking: 440/2797.这次题目似乎比较简单,因为我比赛的时候前三题全做出来了(1:12:39),然后第四题有思路,正在写,没写完,比赛完了写完提交也对了. p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [821]

Performance - Method passes constant String of length 1 to character overridden method

This method passes a constant literal String of length 1 as a parameter to a method, that exposes a similar method that takes a char. It is simpler and more expedient to handle one character, rather than a String. Instead of making calls like: String

Leetcode:Letter Combinations of a Phone Number 手机键盘字母映射

Letter Combinations of a Phone Number: Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Input:Digit string "23" Outp

E - Puzzle( UVA-227)

 Puzzle  A children's puzzle that was popular 30 years ago consisted of a 5x5 frame which contained 24 small squares of equal size. A unique letter of the alphabet was printed on each small square. Since there were only 24 squares within the frame, t

Uva 227-Puzzle 解题报告

题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=163 Puzzle Time limit: 3.000 seconds A children's puzzle that was popular 30 years ago consisted of a 5x5 frame which contained 24 small square

leetcode_Isomorphic Strings

描述: Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characte

Puzzle UVA - 227

A children's puzzle that was popular 30 years ago consisted of a 5×5 frame which contained 24 small squares of equal size. A unique letter of the alphabet was printed on each small square. Since there were only 24 squares within the frame, the frame