今日简单题:#### 242. 有效的字母异位词
思路依旧是String转char[]后排序,再校验是否一致。
要用到的2个方法:
数组排序:Arrays.sort();
数组比较是否一致:Arrays.equals();
我开始想得比较复杂,把char[]排序后,又转成String再用equals方法对比一致性,结果手滑把对比前后String写成同一个了,测试用例一直过不去,顺便测了一下测试用例的分布,正向和逆向用例的比例差不多五五开:
也看到标准答案,用hashmap做,时间和空间复杂度都会降低,只不过习惯上还是直接排序对比实现来的快。
这里再贴一个String.equals()的源码:
/**
* Compares this string to the specified object. The result is {@code
* true} if and only if the argument is not {@code null} and is a {@code
* String} object that represents the same sequence of characters as this
* object.
*
* @param anObject
* The object to compare this {@code String} against
*
* @return {@code true} if the given object represents a {@code String}
* equivalent to this string, {@code false} otherwise
*
* @see #compareTo(String)
* @see #equalsIgnoreCase(String)
*/
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}