leetcode 387. First Unique Character in a String

来源:互联网 发布:seo的营销方法 编辑:程序博客网 时间:2024/06/09 14:01

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.

方法:扫描两次,第一次记录次数,第二次给出位置、 我自己用的map,但是用数组感觉更合适。

public class Solution {    public int firstUniqChar(String s) {        char[] ch = s.toCharArray();        int count[] = new int[26];        for(char c : ch){            count[c-'a']++;        }       for(int i=0;i<ch.length;i++){           if(count[ch[i]-'a']==1){               return i;           }       }        return -1;            }}


0 0
原创粉丝点击