日期:2014-05-20 浏览次数:20837 次
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
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);