package com.yenange.test1;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CountSameChar {
//http://topic.csdn.net/u/20100711/15/94889215-c666-4716-a6b5-1c0c8446db35.html
// 1. 一个字符串参数(value)由字母(a-z,A-Z)组成,且最大字符位数为40,
// 要求写一个函数(maxLength)返回该参数中连续相同字母的最大个数及该字母,
// 如果最大位数有多个,则返回第一个。例:字符串“aaaddxxxxddddxxxx”,返回值为:“x,4”。
// 要求:请考虑代码执行的效率并注意编码的风格。
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入一个字符串");
String str = input.next();
System.out.println(maxLength3(str));
}
/** 自己做的, 思路清晰, 绝对正确, 但代码不够精练 */
private static String maxLength(String str) {
int tempCount = 0, maxCount = 0;
char tempChar = ' ', maxChar = ' ';
String result = "输入串有错!";
if (str.length()>40) {
return result;
}
while (str.length() > 0) {
tempChar = str.charAt(0);
tempCount = 0;
if ( !(tempChar>='a' && tempChar<='z') && !(tempChar>='A' && tempChar<='Z')) {
return result;
}
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == tempChar) {
tempCount++;
} else {
break;
}
}
str = str.substring(tempCount);
if (tempCount > maxCount) {
maxCount = tempCount;
maxChar = tempChar;
}
}
return "way1:"+maxChar + "," + maxCount;
}
/** 别人做的, 惊为天人, 但正则表达式需要改进一下
* (测试aaaabbbbbbbaaaaaaaaabbbbbbddddddddd有问题) */
public static String maxLength2(String s) {
String rs = "";
Pattern p = Pattern.compile("([a-z|A-Z])//1+");
Matcher m = p.matcher(s);
while (m.find()) {
rs = rs.length() > m.group().length() ? rs : m.group();
}
if (rs.length() > 1) {
return "way2:"+rs.substring(0, 1) + ",," + rs.length();
} else {
return "GOD";
}
}
/** 别人做的, 小巧精悍, 原来的有问题, 修改了一下 */
public static String maxLength3(String str) {
char[] array = str.toCharArray();
char ch = array[0],maxCh = array[0];
int count = 1,maxCount =1;
String result = "输入串有错!";
if (str.length()>40) {
return result;
}
for (int i = 1; i < array.length ; i++) {
if ( !(array[i]>='a' && array[i]<='z') && !(array[i]>='A' && array[i]<='Z')) {
return result;
}
if (ch == array[i]) {
count++;
if (maxCount < count) {
maxCount = count;
maxCh = ch;
}
} else {
count = 1;
ch = array[i];
}
}
return "way3:"+maxCh + "," + maxCount;
}
}