日期:2014-05-20  浏览次数:20677 次

字符串的问题,高手快来!!
写一个方法,2)         返回一个字符串中字符连续出现次数最多的字符,3)         及其出现的次数,4)         如果多个字符出现的次数同样最多,返回第一个字符。
例如:aaafffxxxxxx           返回结果为     (   x     ,     6)
  Aaabbbccc               返回结果为   (b     ,     3)


------解决方案--------------------
首先想到遍历了
------解决方案--------------------
先排序,然后如果第一个和下一个相等,CONTINUE,COUNT++
,如果该字符与下一个字符不等,输出COUNT值与该字符,并将COUNT置0
------解决方案--------------------
方法有一个,不过好像不事太好。

import java.util.*;
public class ChongDie {
public String getMost(String str){

List list = new ArrayList();
StringBuffer temp = new StringBuffer( " "+str.charAt(0));

//将每一组连续的数字写入集合中
for(int i=1;i <str.length();i++){
if(str.charAt(i)==str.charAt(i-1)){
temp.append(str.charAt(i));
}else{
list.add(temp.toString());
temp = new StringBuffer( " "+str.charAt(i));
}
if(i==str.length()-1){
list.add(temp.toString());
}
}
//检查集合中数量最多的一组
Iterator it = list.iterator();
int count=0;
String fin = null;
while(it.hasNext()){
String c=(String)it.next();
if(c.length()> count){
count = c.length();
fin = c;
}
}
return fin.toString();
}
public static void main(String[] args){
ChongDie cd = new ChongDie();
String fin = cd.getMost( "aaabbbbbcadefffffffxxxxxxxgg ");
System.out.println( " "+fin.charAt(0)+ ", "+fin.length());
} //result: f,7
}


------解决方案--------------------

public class Test {

public static void main(String[] args)
{
Test test = new Test();
test.test( "a ");
}

public void test(String str)
{
byte[] barray = str.getBytes();
byte b=0;
int count = 0;
int tempCount = 0;
for (int i = 0; i < barray.length; i++) {

if(i> 0)
{
if(barray[i]==barray[i-1])
{
++tempCount;
}
else
{
tempCount = 1;
}
}
else
{
++tempCount;
}
if(count <tempCount)
{
count = tempCount;
b = barray[i];
}
}
System.out.println( "char--> "+(char)b+ "\ncount--> "+count);
}
}

------解决方案--------------------
public void fn(String s){
boolean flag=true;
int n=1,m=0;
char c= '\0 ';
for(int i=1;i <s.length();i++){
if(s.charAt(i)==s.charAt(i-1)){
n++;
}else{
flag=false;
if(m <n){
m=n;
c=s.charAt(i-1);
n=1;
}else{
n=1;
}
}
}
if(flag==true){
System.out.println(s.charAt(0)+ " "+n);
}else{
if(n> m){
System.out.println(s.charAt(s.length()-1)+ " "+n);