
把 s 分割成子字符串,每个子字符串中不能有重复的字母。
问最少可以分成多少个子字符串。
思路:
从左到右遍历 s, 记录substring中已经出现过的字母,出现重复字母时开启新的子字符串。
既然要记录是否出现重复字母,首选hashSet.
因为只有小写英文字母,所以用长度为26的数组代替hashSet.
每次记录下一个substring开始的下标。
不要忘了最后到结尾处也是一个substring.
class Solution {
int res = 0;
public int partitionString(String s) {
int n = s.length();
int i = 0;
while(i < n) {
i = partition(s,i,n);
}
return res;
}
int partition(String s, int st, int e) {
int[] cnt = new int[26];
int i = 0;
for(i = st; i < e; i++) {
if(cnt[s.charAt(i)-'a'] > 0) {
res ++;
return i;
}
cnt[s.charAt(i)-'a'] ++;
}
res ++; //到结尾处也是一个substring
return i;
}
}
还有一种更简洁的方法,用整数的bit位代替hashSet.
顺便介绍下,
1 << ‘a’ 相当于1左移1位,同理 1 << ‘b’ 相当于1左移2位,
所以把整数的 1 << 字母 位 置1来表示对应的字母是不是出现过。
hashSet.add(字母)就相当于 整数与(1 << 字母)做异或操作(字母位 置为1)。
public int partitionString(String s) {
int map = 0;
int res = 0;
for(char ch : s.toCharArray()) {
if((map & (1 << ch)) > 0) {
res ++;
map = 0;
}
map ^= (1 << ch);
}
return ++res;
}
该文章讨论了一种算法问题,即如何将包含小写字母的字符串s分割成不含有重复字母的子字符串,且要求最少的分割数量。文中提出了两种解决方案,一种是使用哈希集(用长度为26的数组实现)来跟踪已出现的字母,另一种是利用整数的位操作来替代哈希集,通过异或操作判断字母是否出现过。这两种方法都是从左到右遍历字符串,遇到重复字母时开始新的子字符串。
653

被折叠的 条评论
为什么被折叠?



