Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

387. First Unique Character in a String #72

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

方法一:建立一个数组储存每个字母出现次数 public class Solution { public int firstUniqChar(String s) { int[] flag = new int[26]; for(int i = 0; i < s.length(); i++) { flag[s.charAt(i)-'a']++; } for(int i = 0; i < s.length(); i++) { if(flag[s.charAt(i)-'a'] == 1) return i; } return -1; } }

方法二: 建立map存储每个字母出现的次数 public class Solution { public int firstUniqChar(String s) { if(s.length() == 0) return -1; HashMap<Character, Integer> map = new HashMap<>(); for(int i = 0; i < s.length(); i++) { if(map.containsKey(s.charAt(i))) { int value = map.get(s.charAt(i)); value++; map.put(s.charAt(i), value); } else { map.put(s.charAt(i), 1); //return i; } }

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

    return -1;
}

}