【剑指offer】【第一个只出现一次的字符】hanhMap&LinkedHashMap

题目描述

在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置

解题代码:

public class Solution {
    public int FirstNotRepeatingChar(String str) {
        LinkedHashMap map = new LinkedHashMap<>();

        int strLength = str.length();
        int result = -1;

        if (strLength>0) {
            for (int i=0; ichar c = str.charAt(i);
                if (map.get(c) == null) {
                    map.put(c,1);
                } else {
                    int num = map.get(c)+1;
                    map.put(c, num);
                }
            }

            for (int j = 0; j < str.length(); j++) {
                if (map.get(str.charAt(j))==1) {
                    result = j;
                    break;
                }
            }
        }
        return result;
    }
}

你可能感兴趣的:(java,剑指offer)