剑指offer 34.第一个只出现一次的字符

剑指offer 34.第一个只出现一次的字符

题目

在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).

思路

这种统计数量的,优先拿hashmap,遍历时若不存在,直接放入,存在的话,数字加一。
最后按照字符串中的顺序遍历一下,若次数为1直接输出。

代码

  public int FirstNotRepeatingChar(String str) {
    if (str == null || str.length() == 0) {
      return -1;
    }
    HashMap<Character, Integer> map = new HashMap<>();
    StringBuffer que = new StringBuffer(str);
    for (int i = 0; i < que.length(); i++) {
      char temp = que.charAt(i);
      if (map.containsKey(temp)) {
        int num = map.get(temp);
        map.put(temp, ++num);
      } else {
        map.put(temp, 1);
      }
    }
    for (int i = 0; i < que.length(); i++) {
      if (map.get(que.charAt(i)) == 1) {
        return i;
      }
    }
    return -1;
  }

猜你喜欢

转载自www.cnblogs.com/blogxjc/p/12411029.html