34.第一个只出现一次的字符(java)

题目描述

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

解题思路

先遍历一遍,使用HashMap保存字母和次数。第二次遍历碰到key=1的直接返回。

import java.util.HashMap;
public class Solution {
    public int FirstNotRepeatingChar(String str) {
        HashMap<Character,Integer> map=new HashMap<Character,Integer>();
        for(int i=0;i<str.length();i++)
        {
            char c = str.charAt(i);
            if(map.containsKey(c))
            {
                int times = map.get(c);
                times++;
                map.put(c,times);
            }
            else
                map.put(c,1);
        }
         for(int i=0;i<str.length();i++)
       {
           char c=str.charAt(i);
          if(map.get(c)==1)
           return i;
       }
       return -1;
}
}

自己出现的问题

hashmap的使用问题:

https://www.cnblogs.com/hanlk/p/11229058.html

发布了43 篇原创文章 · 获赞 0 · 访问量 450

猜你喜欢

转载自blog.csdn.net/gaopan1999/article/details/104553359