首页 > 学院 > 开发设计 > 正文

【Leetcode】387. First Unique Character in a String

2019-11-06 08:22:30
字体:
来源:转载
供稿:网友

方法一:

思路:Map——O(nlogn)

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

Runtime:137ms

方法二:

思路:数组——O(n)

public class Solution {    public int firstUniqChar(String s) {        int count[] = new int[26], len = s.length();        for (int i = 0; i < len; i++)         	count[s.charAt(i) - 'a']++;	   	for (int i = 0; i < len; i++)         	if (count[s.charAt(i) - 'a']== 1)         		return i;	    return -1;    }}

Runtime:23ms


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表