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)

 class Solution {
public int uniqueLetterString(String S) {
int[] last = new int[26];
int[] secondLast = new int[26];
Arrays.fill(last, -1);
Arrays.fill(secondLast, -1); int dp = 0;
int result = 0;
for(int i = 0; i < S.length(); ++i) {
int a = S.charAt(i) - 'A';
dp = dp + (i -last[a]) - (last[a] - secondLast[a]);
result += dp;
secondLast[a] = last[a];
last[a] = i;
} return result;
}
}

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

 class Solution {
public int uniqueLetterString(String S) {
Map<Character, List<Integer>> charIndex = new HashMap<>();
int n = S.length();
for(int i = 0; i < n; ++i) {
char c = S.charAt(i);
if(!charIndex.containsKey(c)) {
charIndex.put(c, new ArrayList<Integer>());
}
charIndex.get(c).add(i);
} long result = 0;
long mod = (long)1e9+7; for(List<Integer> positions: charIndex.values()) { for(int i = 0; i < positions.size(); ++i) {
int prev = i > 0? positions.get(i-1) : -1;
int next = i < positions.size()-1? positions.get(i+1) : n; int curr = positions.get(i);
result = (result + (curr-prev) * (next - curr))%mod;
}
} return (int)result;
}
}

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)

 class Solution {
public int uniqueLetterString(String S) {
int n = S.length();
int[] charIndex = new int[26];
Arrays.fill(charIndex, -1); int[] prev = new int[n];
for(int i = 0; i < n; ++i) {
int a = S.charAt(i) - 'A';
prev[i] = charIndex[a];
charIndex[a] = i;
} Arrays.fill(charIndex, n);
int[] next = new int[n];
for(int i = n-1; i >= 0;--i) {
int a = S.charAt(i) - 'A';
next[i] = charIndex[a];
charIndex[a] = i;
} int result = 0;
int mod = (int)(1e9) + 7; for(int i = 0; i < n; ++i) {
result = (result + (i - prev[i])*(next[i] - i))%mod;
} return result;
}
}

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.

Unique Letter String LT828的更多相关文章

  1. [Swift]LeetCode828. 独特字符串 | Unique Letter String

    A character is unique in string S if it occurs exactly once in it. For example, in string S = " ...

  2. LeetCode828. Unique Letter String

    https://leetcode.com/problems/unique-letter-string/description/ A character is unique in string S if ...

  3. 【leetcode】828. Unique Letter String

    题目如下: A character is unique in string S if it occurs exactly once in it. For example, in string S = ...

  4. [LeetCode] 828. Unique Letter String 独特字符串

    A character is unique in string S if it occurs exactly once in it. For example, in string S = " ...

  5. ORA-00001: unique constraint (string.string) violated 违反唯一约束条件(.)

    ORA-00001: unique constraint (string.string) violated   ORA-00001: 违反唯一约束条件(.) Cause: An UPDATE or I ...

  6. Swift LeetCode 目录 | Catalog

    请点击页面左上角 -> Fork me on Github 或直接访问本项目Github地址:LeetCode Solution by Swift    说明:题目中含有$符号则为付费题目. 如 ...

  7. leetcode array解题思路

    Array *532. K-diff Pairs in an Array 方案一:暴力搜索, N平方的时间复杂度,空间复杂度N 数组长度为10000,使用O(N平方)的解法担心TLE,不建议使用,尽管 ...

  8. All LeetCode Questions List 题目汇总

    All LeetCode Questions List(Part of Answers, still updating) 题目汇总及部分答案(持续更新中) Leetcode problems clas ...

  9. leetcode hard

    # Title Solution Acceptance Difficulty Frequency     4 Median of Two Sorted Arrays       27.2% Hard ...

随机推荐

  1. Spring Boot实现文件下载功能

    我们只需要创建一个控制器(Controler)文件,即Controller目录下的File_Download.java,其完整目录如下: @Controller public class File_D ...

  2. for循环,数字类型,字符串类型

    for 循环: l=['a','b','c'] for i in l : print(i) while循环和for循环 while循环:条件循环,循环的次数取决于条件何时为False for循环:循环 ...

  3. [HTML]音乐自动播放(兼容微信)

    文件下载:音乐自动播放(兼容微信).zip   <!DOCTYPE html> <html> <head> <meta charset="utf-8 ...

  4. C#控件——批量化隐藏或显示同类型控件

    当一个页面中添加了许多同类型控件,当需要控制这些控件进行显示或隐藏的时候,需要一个个的将Visible属性设置为false,十分不方便, 后通过论坛受一位大神(至于叫什么忘了)的启发,通过建立控件数组 ...

  5. 什么是P2P流标

    1.被动流标:在规定的投标时间内,一般是7天,没有凑齐这笔借款,就流标了: 2.主动流标:借款人或平台原因,将为投满的标下架,做流标处理 介绍: 对于投资者来说,在投资P2P理财的时候,可能会遇到过流 ...

  6. 腾讯基于Kubernetes的企业级容器云平台GaiaStack (转)

    GaiaStack介绍 GaiaStack是腾讯基于Kubernetes打造的容器私有云平台.这里有几个关键词: 腾讯:GaiaStack可服务腾讯内部所有BG的业务: Kubernetes:Gaia ...

  7. Java demo之时间

    jdk原生 public class Start { public static void main(String[] args) { SimpleDateFormat simpleDateForma ...

  8. 关于MVC工厂模式的增删改查sql存储过程

    这里MVC中用到了反射,工厂,泛型,接口 在搭建框架的时候,除了MVC的三层以外,还有泛型的接口层和工厂层 下面是dal层调用sql存储过程,增删改查,dal层继承了接口层,实现了接口层里面的方法 1 ...

  9. 云笔记项目-Spring事务学习-传播Requried

    在准备好前期的项目搭建后,接下来就一个个的测试,首先测试事务传播的Required Service层两个实现类 Service层两个实现类,只是更换了方法事务传播的属性,其他都一样,后续测试也只修改传 ...

  10. C#字符串和数组互转

    string str = "a,b,c,d,e";             string[] strArray = str.Split(','); //字符串转数组         ...