242. Valid Anagram

242. Valid Anagram

Problem

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Solution

两数组相等时,直接遍历两个数组并记录各个字符出现的数量。
一个数组遍历时用做加法,另一个做减法。
如果最后每个字符出现的数量均为0,则返回真。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length()!=t.length()){
return false;
}
int[] dic = new int[26];
for (int i = 0; i < s.length(); i++){
dic[s.charAt(i)-'a']++;
dic[t.charAt(i)-'a']--;
}

for(int num : dic){
if ( num != 0 ){
return false;
}
}
return true;
}
}
387. First Unique Character in a String

387. First Unique Character in a String

Problems

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

Solution

遍历,数组统计记录出现次数。
如果数组未记录过,则将其index添加进列表中保存。

遍历列表,如果数组统计结果为1,则返回对应的index。
否则返回-1。

Code 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int firstUniqChar(String s) {
List<Integer> arr = new ArrayList<>();
int[] bin = new int[26];

for(int i = 0; i < s.length(); i++){
if(bin[s.charAt(i) - 'a'] == 0) arr.add(i);
bin[s.charAt(i) - 'a']++;
}

for(int i = 0; i < arr.size(); i++){
if(bin[s.charAt(arr.get(i)) - 'a'] == 1) return arr.get(i);
}

return -1;
}
}

Solution

遍历,建立哈希表,记录出现次数。
再次遍历,如果出现次数为1,则返回下标。

Code 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int firstUniqChar(String s) {
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
for ( int i = 0; i < s.length(); i++ ){
char curChar = s.charAt(i);
if ( !map.containsKey(curChar) ){
map.put(curChar, 1);
}
else{
map.put(curChar, map.get(curChar)+1);
}
}

for ( int i = 0; i < s.length(); i++ ){
char curChar = s.charAt(i);
if ( map.get(curChar) == 1 ){
return i;
}
}
return -1;
}
}