当前位置:网站首页>Leetcode- first unique character in string - simple

Leetcode- first unique character in string - simple

2022-06-13 05:48:00 AnWenRen

title :387 The first unique character in the string - Simple

subject

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

Example 1

s = "leetcode"
 return  0

Example 2

s = "loveleetcode"
 return  2

Tips

** Tips :** You can assume that the string contains only lowercase letters .

Code Java

//  This method has high time complexity 
public int firstUniqChar(String s) {
    
    // 1  use map key Save characters  value Save the index 
    // 2  If there's a repetition   Will value Value to length
    // 3  Judge map Is it empty   If empty   Go straight back to  -1
    // 4  Traverse map  Find the smallest value  If the last is length  return -1
    int count = s.length();
    HashMap map = new HashMap();
    for (int i = 0; i < s.length(); i++) {
    
        if (map.put(s.charAt(i), i) != null) {
    
            map.put(s.charAt(i), count);
        }
    }
    if (map.size() == 0)
        return -1;
    for (Object value : map.values()) {
    
        int x = (int) value;
        if (x < count) {
    
            count = x;
        }
    }
    if (count != s.length())
        return count;
    else
        return -1;
}
//  Two for -  More slowly 
public int firstUniqChar1(String s) {
    
    for (int i = 0; i < s.length(); i++) {
    
        int j;
        for (j= 0; j < s.length(); j++) {
    
            if (j == i)
                continue;
            if (s.charAt(i) == s.charAt(j))
                break;
        }
        if (j == s.length()) {
    
            return i;
        }
    }
    return -1;
}
//  An optimization method 1  It's still slow. 
public int firstUniqChar2(String s) {
    
    HashMap<Character, Integer> map = new HashMap();
    for (int i = 0; i < s.length(); i++) {
    
        if (map.put(s.charAt(i), i) == null) {
    
            map.put(s.charAt(i), 1);
        } else {
    
            map.put(s.charAt(i), (int) map.get(s.charAt(i)) + 1);
        }
    }
    for (int i = 0; i < s.length(); ++i) {
    
        if (map.get(s.charAt(i)) == 1) {
    
            return i;
        }
    }
    return -1;
}
原网站

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