5.找出字符串是最长的子串,要求子串中的所有字符都相同:如"asdfaahellobbsferheeer"  返回结果应该为eee;

解决方案 »

  1.   

    public class asd {
    public static void main(String[] args) {
    String s = "asdfaahellobbsferheeer";
    String maxStr="";
    int maxLen = 0;
    String currentStr ="";
    int currentLen=0;
    char c = s.charAt(0);
    for(int i=0;i<s.length();i++){
    if(c == s.charAt(i)){
    currentStr+=c;
    currentLen++;
    }else{
    if(currentLen>maxLen){
    maxStr=currentStr;
    maxLen=currentLen;
    c=s.charAt(i);
    currentStr=c+"";
    currentLen=1;
    }else{
    c=s.charAt(i);
    currentStr=c+"";
    currentLen=1;
    }
    }
    }
    System.out.println(maxStr);
    }
    }搂住试试 
      

  2.   


    package corejava.day01;public class CheckLongString {
        
    public static void main(String[] args) {
    String test="AAAbbbcccdfg33333333333333ggegegeggdfffffffgdergeg";
    String result =getLongString(test);
    System.out.println(""+result);
    }
    private static String getLongString(String test) {
    int index =test.length();
    char begin =test.charAt(0);
    char last = 0 ;
    int beforenumber =0;
    int nownumber =1;
    for(int i=1;i<index;i++){
    if(begin==test.charAt(i)){
    nownumber++;
    }
    else{
    if(nownumber<beforenumber){
    begin=test.charAt(i);
        nownumber=1;
    continue;
    }
    last=begin;
    beforenumber=nownumber;
    begin=test.charAt(i);
        nownumber=1;
    }
    }
    StringBuffer ss =new StringBuffer();
    for(int i=0;i<beforenumber;i++){
    ss.append(last+"");
    }
    return ss.toString();
    }}输出结果33333333333333
      

  3.   

    String a = "abcdsdfd";
    char ch = '0';
    String chb = "";
    String chc = "";
    for (int i = 0; i < a.length(); i++) {
    if(ch == a.charAt(i)){
    chb += a.charAt(i);
    }else{
    ch = a.charAt(i);
    if(chc.length() <= chb.length()){
    chc = chb;
    }
    chb = "";
    }
    }
    return chc;
      

  4.   

    for example
    String s = "asdfaahellobbsferheeer";
    StringBuilder buf = new StringBuilder();
    String result = "";
    int max = 0;
    for (char c : s.toCharArray()) {
        if (buf.length() > 0) {
            if (buf.charAt(0) != c) {
                if (buf.length() > max) {
                    max = buf.length();
                    result = buf.toString();
                }
                buf.delete(0, buf.length());
            }
        }
        buf.append(c);
    }
    if (buf.length() > max) {
        result = buf.toString();
    }
    System.out.println(result);