判断字符串是否唯一(力扣)
程序员文章站
2024-02-21 14:15:03
...
import java.util.HashMap;
public class Test {
public static void main(String[] args) {
System.out.println(test1("abcde"));
System.out.println(test1("abcdee"));
System.out.println(test2("abcde"));
System.out.println(test2("abcdee"));
}
public static boolean test1(String str){
HashMap<Character ,Integer> hashMap = new HashMap<>();
for (char aChar : str.toCharArray()) {
if (hashMap.get(aChar) == null){
hashMap.put(aChar,1);
}else {
return false;
}
}
return true;
}
public static boolean test2(String str){
for (int i = 0; i < str.length(); i++) {
String s = str;
//用空去替代每个字符,如果数组长度一次性减少了多个(大于一),则说明有重复字符串。
s = s.replace(String.valueOf(str.charAt(i)),"");
if (s.length() != str.length() - 1){
return false;
}
}
return true;
}
}
上一篇: 异常问题-异常处理
下一篇: 每日一题——JS闭包