我实现了打字训练器,并想startsWith()
用特定的规则创建我的特殊 String 方法。例如:'-'
char 应该等于任何长连字符('‒'
等)。此外,我将为特殊重音字符添加其他规则(e 等于é,但不é等于 e)。
public class TestCustomStartsWith {
private static Map<Character, List<Character>> identityMap = new HashMap<>();
static { // different hyphens: ‒, –, —, ―
List<Character> list = new LinkedList<>();
list.add('‒');
list.add('–'); // etc
identityMap.put('-', list);
}
public static void main(String[] args) {
System.out.println(startsWith("‒d--", "-"));
}
public static boolean startsWith(String s, String prefix) {
if (s.startsWith(prefix)) return true;
if (prefix.length() > s.length()) return false;
int i = prefix.length();
while (--i >= 0) {
if (prefix.charAt(i) != s.charAt(i)) {
List<Character> list = identityMap.get(prefix.charAt(i));
if ((list == null) || (!list.contains(s.charAt(i)))) return false;
}
}
return true;
}
}
我可以用char替换各种长连'-'
字符,但是如果有更多规则,恐怕替换会太慢。
我该如何改进这个算法?