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;
        }
    
  • 相关阅读:
    Hadoop学习笔记(1) ——菜鸟入门
    自己动手做个智能小车(8)[终]
    自己动手做个智能小车(7)
    自己动手做个智能小车(6)
    CSS动画
    smarty的缓冲
    smarty模板
    修改登录密码
    登录验证码
    phpcms
  • 原文地址:https://www.cnblogs.com/wxshi/p/7683759.html
Copyright © 2011-2022 走看看