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. hadoop 二次排序的一些思考

    先说一下mr的二次排序需求: 假如文件有两列分别为name.score,需求是先按照name排序,name相同按照score排序 数据如下: jx 20 gj 30 jx 10 gj 15 输出结果要 ...

  2. 关于单元测试时加载spring-context.xml文件的问题

    在进行web开发的时候,通常我们都会使用Spring框架,使用spring容器管理java bean. 而spring的配置文件有时候放在classpath下面,有时候放在WEB-INF下面. 一般在 ...

  3. js学习2

    1.打开新窗体 -window.open([URL], [窗口名称], [参数字符串]) - 窗口名称: _blank:在新窗口显示目标网页 _self:在当前窗口显示目标网页 _top:框架网页中在 ...

  4. Java学习随笔(2)--爬虫--天气预报

    public class Spiderweather { public static void main(String[] args) { List<String> list = null ...

  5. redis+thinkphp5的注册、登陆、关注基础例子

    最近初步接触redis,结合thinkphp5与redis,写了一个用户注册的基础例子,用于学习. 这个例子是结合了兄弟连的redis视频,最后两节的内容写的:https://study.163.co ...

  6. 函数function

    function add(x,y,z){ sum = x + y +z; document.write(x+"+"+y+"+"+z+"="+ ...

  7. vue--组件基础

    组件是可复用的 vue 实例,它与new Vue 接收相同的参数,例如:data.methods.computed.watch 以及生命周期钩子.除了 el 等. 1.组件注册必须有一个组件名. 组件 ...

  8. Linux seq_printf输出内容不完整的问题

    Linux seq_printf输出内容不完整的问题 写在前面的话:这是多年前在项目中遇到的问题,作为博客的开篇之作,有不足之处,请各位大侠斧正!谢谢! seq_file接口介绍 有许多种方法能够实现 ...

  9. servlet的继承关系

    一.servlet的继承关系 1.servlet程序是sun公司开发用于web资源技术,任何一个类只需要实现了servlet接口,那么就可以成为servlet程序 2.继承体系: ---------- ...

  10. ORACLE升级11g以上之前版本的wm_concat()函数失效

    先执行: create or replace type string_sum_obj as object ( --聚合函数的实质就是一个对象 sum_string ), static function ...