第一个只出现一次的字符(字符串)

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

思路一:

public class Solution {
    public int FirstNotRepeatingChar(String str) {
        if (str == null || str.length() == 0)
            return -1;
        char[] chars = str.toCharArray();
        int[] res = new int['z' + 1];
        for (char c : chars)
            res[(int) c]++;
        for (int i = 0; i < chars.length; i++)
        {
            if (res[(int) chars[i]] == 1)
                return i;
        }
        return  -1;
    }
}

思路二:

public class Solution {
    public int FirstNotRepeatingChar(String str) {
        if (str == null || str.length() == 0) return -1;
        char[] chars = str.toCharArray();
        int i = 0;
        int res = -1;
        for (; i < chars.length; i++)
        {
            if (chars[i] != '0')
            {
                int count = 1;
                for (int j = i + 1; j < chars.length; j++)
                {
                    if (chars[i] == chars[j]) {
                        count++;
                        chars[j] = '0';
                    }
                }
                if (count == 1)
                {
                    res = i;
                    break;
                }
            }
        }
        return res;
    }
}

思路三:

import java.util.*;

public class Solution {
    public int FirstNotRepeatingChar(String str) {
        if (str == null || str.length() == 0) return -1;
        LinkedHashMap map = new LinkedHashMap<>();
        for (int i = 0; i < str.length(); i++)
        {
            if (map.containsKey(str.charAt(i)))
            {
                int time = map.get(str.charAt(i));
                map.put(str.charAt(i), ++time);
            }
            else
                map.put(str.charAt(i), 1);
        }
        int i = 0;
        for (; i < str.length(); i++)
        {
            char c = str.charAt(i);
            if (map.get(c) == 1) {
                return i;
            }
        }
        return -1;
    }
}



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