题目:
Longest Repeating Character Replacement:
Given a string that consists of only uppercase English letters, you can replace any letter in the string with another letter at most k times. Find the length of a longest substring containing all repeating letters you can get after performing the above operations.
代码:
package com.cl.test1;
import java.util.ArrayList;
import java.util.List;
/**
* Given a string that consists of only uppercase English letters,
* you can replace any letter in the string with another letter at most k times.
* Find the length of a longest substring containing all repeating letters
* you can get after performing the above operations.
* @author CL
*
*/
public class ReplaceDuplicatedLetter {
public int characterReplacement(String s, int k) {
if(s==""||s.length()==0){
return 0;
}
char[] cs=s.toCharArray();
List<StrAndTimes> list = new ArrayList<StrAndTimes>();
char c = cs[0];
list.add(new StrAndTimes(c,1));
int j=0,max=0,cur=0,tempK;
StrAndTimes sat=null,tempSat=null;
for(int i=1;i<cs.length;i++){
if(cs[i]==c){
sat = list.get(j);
sat.setN(sat.getN()+1);
}else{
sat = new StrAndTimes(cs[i], 1);
j++;
list.add(sat);
c=cs[i];
}
}
for (StrAndTimes strAndTimes : list) {
System.out.println(strAndTimes);
}
for (int i=0;i<list.size();i++) {
sat=list.get(i);
cur=sat.getN()+k;
//可以
tempK=k;
for(j=i+1;j<list.size();j++){
tempSat=list.get(j);
if(tempSat.getC()==sat.getC()){
cur+=tempSat.getN();
continue;
}else{
tempK-=tempSat.getN();
if(tempK<0)
break;
}
}
if(cur>max){
max=cur;
}
if(max>cs.length){
max=cs.length;
break;
}
}
return max;
}
public static void main(String[] args) {
System.out.println(new ReplaceDuplicatedLetter().characterReplacement("EOEMQLLQTRQDDCOERARHGAAARRBKCCMFTDAQOLOKARBIJBISTGNKBQGKKTALSQNFSABASNOPBMMGDIOETPTDICRBOMBAAHINTFLH", 7));
}
}
class StrAndTimes implements Comparable<StrAndTimes>{
char c;
int n;
public char getC() {
return c;
}
public StrAndTimes(char c, int n) {
super();
this.c = c;
this.n = n;
}
public void setC(char c) {
this.c = c;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
@Override
public int compareTo(StrAndTimes o) {
if(o.getC()==this.getC())
return 0;
else if(this.getC()>o.getC()){
return 1;
}else{
return -1;
}
}
@Override
public String toString() {
return "StrAndTimes [c=" + c + ", n=" + n + "]";
}
}