当前位置: 代码迷 >> J2SE >> 求教字符串类型题目,该如何处理
  详细解决方案

求教字符串类型题目,该如何处理

热度:94   发布时间:2016-04-24 01:13:51.0
求教字符串类型题目

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

------解决方案--------------------
Java code
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();    }}
------解决方案--------------------
for example
Java code
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);
  相关解决方案