zoukankan      html  css  js  c++  java
  • leetcode-字符串中的第一个唯一字符

    给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

    案例:

    s = "leetcode"
    返回 0.
    
    s = "loveleetcode",
    返回 2.
    

    注意事项:您可以假定该字符串只包含小写字母。

    class Solution {
        public int firstUniqChar(String s) {
            char []c=s.toCharArray();
            int len=s.length();
            if(len==1) return 0;
            int hashTable[]=new int[256];     //利用哈希表
            for(int i=0;i<len;i++){
                hashTable[c[i]]++;;
            }
            for(int i=0;i<len;i++){
                if(hashTable[c[i]]==1) return i;
            }
            
            return -1;
        }
    }

    利用数据结构:

    class Solution {
        public int firstUniqChar(String s) {
            char []c=s.toCharArray();
            int len=s.length();
            if(len==1) return 0;
            HashMap<Character,Integer> map=new HashMap();
            for(char cc:c){
                if(!map.containsKey(cc))map.put(cc,1);
                else map.put(cc,2);
            }
            for(int i=0;i<len;i++){
                if(map.get(c[i])==1)return i;
            }
            return -1;
        }
    }
  • 相关阅读:
    【NOI2015】荷马史诗
    Codeforces Round #415 (Div. 2)
    Codeforces Round #408 (Div. 2)
    bzoj3230
    poj1743
    poj1226
    bzoj1295
    bzoj1294
    bzoj1296
    bzoj1239
  • 原文地址:https://www.cnblogs.com/patatoforsyj/p/9501755.html
Copyright © 2011-2022 走看看