zoukankan      html  css  js  c++  java
  • 387.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.
    这道题和169.Majority Element相似,我们先使用Map的方法
    方法一

    public int firstUniqChar(String s) {
                int result =-1;
                Map<Character,Integer> map = new HashMap();
                for(int i = 0; i < s.length();i++)
                {
                    char tmp = s.charAt(i);
                    if(!map.containsKey(tmp))
                        map.put(tmp,1);
                    else
                        map.put(tmp,map.get(tmp) + 1);
                }
                System.out.println(map);
                for(int i = 0; i < s.length();i++)
                {
                    if(map.get(s.charAt(i)) == 1)
                    {
                        result= i;
                        break;
                    }  
                }
                return result;
            }
    

    方法二
    巧妙使用ASCII方法

    public int firstUniqChar(String s) {
            int a[] =  new int[26];
            for(int i = 0; i < s.length();i++)
            {
                a[s.chartAt(i)-'a'] ++;
            }
            for(int i = 0; i < s.length();i++)
            {
                if(a[s.chartAt(i)-'a']==1)
                    return i;
            }
            return -1;
        }
    
  • 相关阅读:
    mysql基础知识
    django知识
    gitlab的CICD搭建记录
    nginx的基础知识
    JAVA基础知识总结——part1
    【Python】python基础练习题_1
    【Docker】——Linux下搭建docker环境
    day3
    python_day2
    python_day1
  • 原文地址:https://www.cnblogs.com/wxshi/p/7683759.html
Copyright © 2011-2022 走看看