当前位置:网站首页>Leetcode advanced path - the first unique character in a string

Leetcode advanced path - the first unique character in a string

2022-06-10 21:18:00 Li_ XiaoJin

 Given a string , Find its first non repeating character , And return its index . If it doesn't exist , Then return to  -1.


 Example :

s = "leetcode"
 return  0

s = "loveleetcode"
 return  2


 Tips : You can assume that the string contains only lowercase letters .
public class FirstUniqueCharacterinaString {
    public static int firstUniqChar(String s) {

        if (s == null || s.length() == 0) {
            return -1;
        }
        if (s.length() == 1) {
            return 0;
        }
        for (int i = 0; i < s.length()-1; i++) {
            if (s.indexOf(s.charAt(i)) == s.lastIndexOf(s.charAt(i))) {
                return i;
            }
        }
        return -1;
    }

    /**
     *  Official solution 
     * @param s
     * @return
     */
    public static int firstUniqChar1(String s) {

        HashMap<Character, Integer> count = new HashMap<Character, Integer>();
        int n = s.length();
        for (int i = 0; i < n; i++) {
            char c = s.charAt(i);
            count.put(c, count.getOrDefault(c, 0) + 1);
        }

        for (int i = 0; i < n; i++) {
            if (count.get(s.charAt(i)) == 1)
                return i;
        }
        return -1;
    }

    public static void main(String[] args) {
        String s = "cc";
//        String s = "";
//        String s = "abc";
        System.out.println(firstUniqChar(s));
    }
}

Copyright: use Creative Commons signature 4.0 International license agreement to license Links:https://lixj.fun/archives/leetcode Advanced road - The first unique character in the string

原网站

版权声明
本文为[Li_ XiaoJin]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101959595683.html