创建一个enum
表示字符类型的 - 您需要一种方法来获取enum
给定字符的字符类型。我确信有比我在下面所做的更好的方法来做到这一点,但这留给读者作为练习。
接下来创建一个方法,该方法采用先前和当前字符并将它们的类型连接成一个唯一的String
.
最后循环输入字符串,嘿presto。
private static enum CharacterType {
UPPER {
@Override
boolean isA(final char c) {
return Character.isUpperCase(c);
}
},
LOWER {
@Override
boolean isA(final char c) {
return Character.isLowerCase(c);
}
},
SPACE {
@Override
boolean isA(final char c) {
return Character.isWhitespace(c);
}
},
UNKOWN {
@Override
boolean isA(char c) {
return false;
}
};
abstract boolean isA(final char c);
public static CharacterType toType(final char c) {
for (CharacterType type : values()) {
if (type.isA(c)) {
return type;
}
}
return UNKOWN;
}
}
private static String getTransitionType(final CharacterType prev, final CharacterType current) {
return prev + "_TO_" + current;
}
public static void main(String[] args) {
final String myString = "AAaaA Aaa AA";
final Map<String, Integer> countMap = new TreeMap<String, Integer>() {
@Override
public Integer put(final String key, final Integer value) {
final Integer currentCount = get(key);
if (currentCount == null) {
return super.put(key, value);
}
return super.put(key, currentCount + value);
}
};
final char[] myStringAsArray = myString.toCharArray();
CharacterType prev = CharacterType.toType(myStringAsArray[0]);
for (int i = 1; i < myStringAsArray.length; ++i) {
final CharacterType current = CharacterType.toType(myStringAsArray[i]);
countMap.put(getTransitionType(prev, current), 1);
prev = current;
}
for (final Entry<String, Integer> entry : countMap.entrySet()) {
System.out.println(entry);
}
}
输出:
LOWER_TO_LOWER=2
LOWER_TO_SPACE=1
LOWER_TO_UPPER=1
SPACE_TO_SPACE=1
SPACE_TO_UPPER=2
UPPER_TO_LOWER=2
UPPER_TO_SPACE=1
UPPER_TO_UPPER=2
对问题内容(825 个字符)运行该方法需要 9 毫秒。