First Unique Character in a String

来源:互联网 发布:防辐射眼镜 知乎 编辑:程序博客网 时间:2024/05/20 18:41

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.


思路:用hashmap统计,再扫一遍;

public class Solution {    public int firstUniqChar(String s) {        if(s == null || s.length() ==0){            return -1;        }                HashMap<Character, Integer> hashmap = new HashMap<Character, Integer>();        for(int i=0; i<s.length(); i++){            char c = s.charAt(i);            if(hashmap.containsKey(c)){                hashmap.put(c, hashmap.get(c)+1);            } else {                hashmap.put(c, 1);            }        }                for(int i=0; i<s.length(); i++){            char c = s.charAt(i);            if(hashmap.get(c) == 1){                return i;            }        }        return -1;    }}
思路2:用array来统计,节省空间,并且快点。

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


0 0
原创粉丝点击