至多包含K个字符的最长子串
class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
int left=0;
int length=0;
//用hm来记录两边包着的 <字母,个数>
HashMap<Character,Integer> hm=new HashMap();
for(int i=0;i<s.length();i++){
if(hm.containsKey(s.charAt(i))){
hm.put(s.charAt(i),hm.get(s.charAt(i))+1);
}else{
hm.put(s.charAt(i),1);
}
if(hm.size()>k){
int value=hm.get(s.charAt(left))-1;
if(value==0){
hm.remove(s.charAt(left));
}else{
hm.put(s.charAt(left),value);
}
left++;
}
length=Math.max(length,i-left+1);
}
return length;
}
}
无重复字符最长子串
class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character,Integer>hm=new HashMap();
//字符,索引
int left=0;
int len=0;
if(s.length()==1) return 1;
for(int i=0;i<s.length();i++){
if(hm.containsKey(s.charAt(i))){
left=Math.max(left,hm.get(s.charAt(i))+1);
}
hm.put(s.charAt(i),i);
len=Math.max(len,i-left+1);
}
return len;
}
}
前K个高频单词
class Solution {
public List<String> topKFrequent(String[] words, int k) {
HashMap<String,Integer> hm=new HashMap();
PriorityQueue<String> pq=new PriorityQueue(
new Comparator<String>(){
public int compare(String o1, String o2) {
if(hm.get(o2)-hm.get(o1)==0){
return o1.compareTo(o2);
}
return hm.get(o2)-hm.get(o1);
}
}
);
for(int i=0;i<words.length;i++){
if(hm.containsKey(words[i])){
hm.put(words[i],hm.get(words[i])+1);
}else{
hm.put(words[i],1);
}
}
Set<String> keyset=hm.keySet();
for(String key:keyset){
pq.offer(key);
}
List<String> list=new ArrayList();
for(int i=0;i<k;i++){
list.add(pq.poll());
}
return list;
}
}
查找共用字符
class Solution {
public List<String> commonChars(String[] words) {
int a[][]=new int[26][words.length];
String str=words[0];
List<String>list=new ArrayList();
for(int i=0;i<words.length;i++){
str=words[i];
for(int j=0;j<str.length();j++){
int st=str.charAt(j)-'a';
a[st][i]++;
}
}
for(int i=0;i<a.length;i++){
int minn=65536;
for(int j=0;j<a[0].length;j++){
minn=Math.min(minn,a[i][j]);
}
while(minn-->0){
StringBuilder sb=new StringBuilder();
char tmp=(char)(i+'a');
sb.append(tmp);
list.add(new String(sb));
}
}
return list;
}
}