上周没刷,这周刷两道,记录一下。
字符串中的第一个唯一字符
问题描述
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
思路
思路1:二重循环遍历,每遍历一位,往后面查找,有重复的就continue,没重复的返回结果。时间复杂度O(n2)
思路2:定义一个类(字符,索引,出现次数),遍历字符串,统计信息存到Map里面,然后放到优先队列中,然后一个个拿出来,返回第一个出现次数为1的字符索引。O(nlogn)。(代码实现)
思路3:两次遍历。一次遍历存储每个字符出现次数,第二次遍历找出第一个出现次数为1的字符。用HashMap。时间复杂度O(2n)
代码实现
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
Map<Character, Integer> map1 = new HashMap<>();
Map<Character, Integer> map2 = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if (map1.containsKey(s.charAt(i))) {
map1.put(s.charAt(i), map1.get(s.charAt(i)) + 1);
} else {
map1.put(s.charAt(i), 1);
}
if (map2.containsKey(t.charAt(i))) {
map2.put(t.charAt(i), map2.get(t.charAt(i)) + 1);
} else {
map2.put(t.charAt(i), 1);
}
}
for (Character c : map1.keySet()) {
if (!map2.containsKey(c) || !map1.get(c).equals(map2.get(c))) {
return false;
}
}
return true;
}
有效的字母异位词
问题描述
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。
思路
思路1:判断两个字符串长度是否相同。分别遍历连个字符串,存字符出现次数到Map。遍历一个Map,看另一个Map是否都有对应数量字符。时间复杂度O(3n)
代码实现
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
Map<Character, Integer> map1 = new HashMap<>();
Map<Character, Integer> map2 = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if (map1.containsKey(s.charAt(i))) {
map1.put(s.charAt(i), map1.get(s.charAt(i)) + 1);
} else {
map1.put(s.charAt(i), 1);
}
if (map2.containsKey(t.charAt(i))) {
map2.put(t.charAt(i), map2.get(t.charAt(i)) + 1);
} else {
map2.put(t.charAt(i), 1);
}
}
for (Character c : map1.keySet()) {
if (!map2.containsKey(c) || !map1.get(c).equals(map2.get(c))) {
return false;
}
}
return true;
}