leetcode[First Unique Character in a String]//待整理多种解法

来源:互联网 发布:sql 父子级联查询 编辑:程序博客网 时间:2024/06/15 12:55

解法一:

public class Solution {//要寻找在字符串中只出现一次的第一个字符的位置,就用Map来统计//然后遍历字符串,找出第一个只出现一次的字符    public int firstUniqChar(String s) {        HashMap<Character, Integer> map = new HashMap<>();        //统计字符串的map        for(int i = 0; i < s.length(); i++){        char c = s.charAt(i);        if(map.containsKey(c)){        map.put(c, map.get(c) + 1);        }        else{        map.put(c, 1);        }        }                //遍历map找出第一个只出现一次的字符        for(int i = 0; i < s.length(); i++){        if(map.get(s.charAt(i)) == 1){        return i;        }        }        return -1;    }}


原创粉丝点击