LeetCode387 First Unique Character in a String

题目

Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.

Examples:

s = “leetcode”
return 0.

s = “loveleetcode”,
return 2.
Note: You may assume the string contain only lowercase letters.
即找到字符串中第一个不重复的字母。

方法一

很自然的想到两次遍历来找到唯一的字符,同时利用字母只有26个的特点减少循环次数。

public int firstUniqChar(String s) {
        if (s.length() == 0) return -1;
        int[] test = new int[s.length()];
        int count = 0;
        int result = -1;
        boolean found = true;
        for (int i = 0; i < s.length() && count < 27; i++) {
            if (test[i] == 1) continue;
            else count++;

            for (int j = i + 1; j < s.length(); j++) {
                if (test[j] == 1) continue;
                if (s.charAt(i) == s.charAt(j)) {
                    found = false;
                    test[i] = 1;
                    test[j] = 1;
                }
            }
            if (found) {
                result = i;
                break;
            }
            found = true;
        }
        return result;
    }

方法二

嵌套循环毫无疑问效率低下,这是想到使用键值对记录每个字母的出现次数,同时利用hashmap去重的特性。

public int firstUniqChar1(String s) {
        if (s.length() == 0) return -1;
        int result = -1;
        Map<Character, Integer> map = new HashMap<>();
        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);
        }
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (map.get(c) == 1) {
                result = i;
                break;
            }
        }
        return result;
    }

虽然简化了步骤,但是map的使用仍然需要较多的时间开销。这是可以使用数组的1~26个位置代表a~z出现的次数。

public int firstUniqChar2(String s) {
        if (s.length() == 0) return -1;
        int result = -1;
        int[] record = new int[26];
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            int index = c - 'a';
            record[index]++;
        }
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (record[s.charAt(i)-'a'] == 1) {
                result = i;
                break;
            }
        }
        return result;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值