题目描述
Given a string s
, find the first non-repeating character in it and return its index. If it does not exist, return -1
.
解题思路
【C++解法】
class Solution {
public:
int firstUniqChar(string s) {
int len = s.size(); //s.length()
int hash[256] = {0};
for (int i=0; i<len; i++) {
hash[s[i]]++;
}
for (int i=0; i<len; i++) {
if (hash[s[i]] == 1) {return i;}
}
return -1;
}
};
【C解法】
int firstUniqChar(char * s){
int len = strlen(s);
int hash[256] = {0};
for (int i=0; i<len; i++) {
hash[s[i]]++;
}
for (int i=0; i<len; i++) {
if (hash[s[i]] == 1) {return i;}
}
return -1;
}
【Java解法】
class Solution {
public int firstUniqChar(String s) {
int[] hash = new int[256];
char[] chs = s.toCharArray();
for (char ch : chs) {
hash[ch]++;
}
for (int i = 0; i < s.length(); i++) {
if (hash[chs[i]] == 1) {
return i;
}
}
return -1;
}
}
【Kotlin解法】
class Solution {
fun firstUniqChar(s: String): Int {
var hash = IntArray(256)
for (ch in s) {
hash[ch.toInt()]++
}
for (i : Int in 0..s.length - 1) {
if (hash[s[i].toInt()] == 1) {
return i;
}
}
return -1;
}
}
【Rust解法】
位运算
impl Solution {
pub fn first_uniq_char(s: String) -> i32 {
let chars = s.as_bytes();
let (mut m2l, mut ms) = (0u32, 0u32);
let mut m2s;
for &c in chars {
let hash = 1 << (c & 0x1f);
m2s = ms & hash;
ms |= hash;
m2l |= m2s;
}
let once = ms ^ m2l;
for i in 0..chars.len() {
if 1 << (chars[i] & 0x1f) & once > 0 {
return i as i32
}
}
-1
}
}
使用Vec
impl Solution {
pub fn first_uniq_char(s: String) -> i32 {
let mut char_vec = vec![0; 256];
s.chars().for_each(|c| { char_vec[c as usize] += 1});
for (i, c) in s.char_indices() {
if char_vec[c as usize] == 1 {
return i as i32;
}
}
-1
}
}
使用HashMap
use std::collections::HashMap;
impl Solution {
pub fn first_uniq_char(s: String) -> i32 {
let mut count: HashMap<char, i32> = HashMap::new();
for l in s.chars() {
if count.contains_key(&l) {
let val = count.get(&l).unwrap();
count.insert(l, val + 1);
} else {
count.insert(l, 1);
}
}
for (i, l) in s.chars().enumerate() {
let val = *count.get(&l).unwrap();
if val == 1 {
return i as i32;
}
}
return -1;
}
}