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)
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的更多相关文章
- [Swift]LeetCode828. 独特字符串 | Unique Letter String
A character is unique in string S if it occurs exactly once in it. For example, in string S = " ...
- LeetCode828. Unique Letter String
https://leetcode.com/problems/unique-letter-string/description/ A character is unique in string S if ...
- 【leetcode】828. Unique Letter String
题目如下: A character is unique in string S if it occurs exactly once in it. For example, in string S = ...
- [LeetCode] 828. Unique Letter String 独特字符串
A character is unique in string S if it occurs exactly once in it. For example, in string S = " ...
- ORA-00001: unique constraint (string.string) violated 违反唯一约束条件(.)
ORA-00001: unique constraint (string.string) violated ORA-00001: 违反唯一约束条件(.) Cause: An UPDATE or I ...
- Swift LeetCode 目录 | Catalog
请点击页面左上角 -> Fork me on Github 或直接访问本项目Github地址:LeetCode Solution by Swift 说明:题目中含有$符号则为付费题目. 如 ...
- leetcode array解题思路
Array *532. K-diff Pairs in an Array 方案一:暴力搜索, N平方的时间复杂度,空间复杂度N 数组长度为10000,使用O(N平方)的解法担心TLE,不建议使用,尽管 ...
- All LeetCode Questions List 题目汇总
All LeetCode Questions List(Part of Answers, still updating) 题目汇总及部分答案(持续更新中) Leetcode problems clas ...
- leetcode hard
# Title Solution Acceptance Difficulty Frequency 4 Median of Two Sorted Arrays 27.2% Hard ...
随机推荐
- 注意source folder与folder是不同的,避免404错误
在整合ssm框架的时候,程序和配置文件都没写错,tomcat也部署成功了,但在访问的时候一直404,web项目自带的index.jap却能正常访问,一直找不到原因,后来发现建立放配置文件的文件夹con ...
- pgsql 常用命令
1.连接到pgsql数据库 psql -U postgres 2.查看所有数据库 \l 3.连接到数据库test \c test 4.查看数据库所有表以及视图 \d 5.查看数据库所有的表 \dt 6 ...
- Java学习之代码块(静态,构造代码块,构造方法)执行顺序
静态代码块 static{ 代码 } 随着类的加载而加载,随类的消失而消失,存在于类中,方法外,最先执行,且只加载1次,可用来加载驱动及初始化对象属性. 构造代码块 { } 也存在于类中, ...
- Golang源码探索(三) GC的实现原理(转)
Golang从1.5开始引入了三色GC, 经过多次改进, 当前的1.9版本的GC停顿时间已经可以做到极短.停顿时间的减少意味着"最大响应时间"的缩短, 这也让go更适合编写网络服务 ...
- java委托
上文讲过观察者模式,尽管已经用了依赖倒转原则,但是"抽象通知者"还是依赖"抽象观察者",也就是说万一没有了抽象观察者这样的接口,通知的功能就完不成了.另一方面, ...
- logstash 切分tomcat日志
以下配置是logstash切分tomcat catalina.out日志. http://grok.qiexun.net/ 分割时先用这个网站测试下语句对不对,能不能按需切割日志. input { ...
- sha256_transform
DECLSPEC void sha256_transform (const u32 *w0, const u32 *w1, const u32 *w2, const u32 *w3, u32 *dig ...
- ssh命令详解
1.简介: Secure Shell(缩写为SSH),由IETF的网络工作小组(Network Working Group)所制定:SSH为一项创建在应用层和传输层基础上的安全协议,为计算机上的She ...
- django restfulwork 源码剖析
概要: 1.restful 规范(建议); 2. django rest framework框架 内容回顾: 1.开发模式; - 普通开发模式(前后端放在一起写) - 前后端分离 好处: 后端一套,前 ...
- Tomcat Server处理一个http请求的过程
Tomcat Server处理一个http请求的过程 假设来自客户的请求为: http://localhost:8080/wsota/wsota_index.jsp 1) 请求被发送到本机端口8080 ...