387. First Unique Character in a String

原题链接:https://leetcode.com/problems/first-unique-character-in-a-string/description/
我的实现:

import java.util.HashMap;
import java.util.Map;

/**
 * Created by clearbug on 2018/2/26.
 *
 * 这道题目是看《剑指offer》面试题50时看到的,然后来 LeetCode 上一搜还有原题,正好刷一下
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.firstUniqChar("leetcode"));
        System.out.println(s.firstUniqChar("loveleetcode"));
    }

    /**
     * 方法一:最黄最暴力的方法了,提交结果竟然是:16.48 %,还有人写的解法效率比这还差。。
     *
     * 时间复杂度:O(n^2)
     * 空间复杂度:O(1)
     *
     * @param s
     * @return
     */
    public int firstUniqChar1(String s) {
        for (int i = 0; i < s.length(); i++) {
            int j;
            for (j = 0; j < s.length(); j++) {
                if (i != j && s.charAt(i) == s.charAt(j)) {
                    break;
                }
            }
            if (j == s.length()) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 方法二:借助哈希表,以空间换时间来提高运行效率,然后提交结果是:3.30 %,fuck 我觉得可能是 LeetCode 跑用例有问题吧
     *
     * 时间复杂度:O(n)
     * 空间复杂度:O(n)
     *
     * @param s
     * @return
     */
    public int firstUniqChar(String s) {
        Map<Character, Integer> map = new HashMap<>(s.length());
        for (int i = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i))) {
                map.put(s.charAt(i), map.get(s.charAt(i)) + 1);
            } else {
                map.put(s.charAt(i), 1);
            }
        }

        for (int i = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i)) && map.get(s.charAt(i)) == 1) {
                return i;
            }
        }

        return -1;
    }
}
原文地址:https://www.cnblogs.com/optor/p/8633435.html