I'm Prime

十方三世,尽在一念

View on GitHub

leetcode 笔记


题目描述

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

示例:

s = "leetcode"
返回 0

s = "loveleetcode"
返回 2

提示:你可以假定该字符串只包含小写字母。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

code

class Solution {
public:
    int firstUniqChar(string s) {
        vector<int> count(26, 0);
        for(char i : s) count[i - 'a']++;
        
        for (int i = 0, size = s.size(); i < size; i++)
        if(count[s[i] - 'a'] == 1) return i;

        return -1;
    }
};

一刀流

fun firstUniqChar(s: String): Int = s.fold(IntArray(26)) { acc, c -> acc.also { it[c - 'a']++ }}.let { cnt -> s.indexOfFirst { cnt[it - 'a'] == 1 }}
class Solution {
    fun firstUniqChar(s: String): Int = s.fold(IntArray(26)) { acc, c ->
        acc.also { it[c - 'a']++ }
    }.let { cnt ->
        s.indexOfFirst { cnt[it - 'a'] == 1 }
    }
}

一刀流。 但是这题scala的一刀流没什么优势,纯粹为了一刀而一刀。

def firstUniqChar(s: String): Int = s.zipWithIndex.foldLeft(Array.fill(26)((0, 0)))((acc, i) => {acc(i._1 - 'a') = (i._2, acc(i._1 - 'a')._2 + 1); acc}).foldLeft(-1)((acc, i) => if(i._2 == 1 && (acc == -1 || i._1 < acc)) i._1 else acc)
object Solution {
  def firstUniqChar(s: String): Int = s.zipWithIndex.foldLeft(Array.fill(26)((0, 0)))(
    (acc, i) => {acc(i._1 - 'a') = (i._2, acc(i._1 - 'a')._2 + 1); acc}
  ).foldLeft(-1)((acc, i) => if(i._2 == 1 && (acc == -1 || i._1 < acc)) i._1 else acc)
}

常规写

object Solution {
  def firstUniqChar(s: String): Int = {
    val cnt = Array.fill(26)(0)
    s.foreach(ch => cnt(ch - 'a') += 1)
    s.indexWhere(ch => cnt(ch - 'a') == 1)
  }
}

scala, 一刀流没意义

pub fn first_uniq_char(s: String) -> i32 {s.chars().enumerate().fold(HashMap::new(), |mut m, (index, ch)| {m.entry(ch).and_modify(|(_, i): &mut (usize, i32)| *i += 1).or_insert((index, 1));m}).values().fold(-1, |ans, &(index, count)| {if count == 1 && (ans == -1 || (index as i32) < ans) {index as i32} else {ans}})}
use std::collections::HashMap;

impl Solution {
    pub fn first_uniq_char(s: String) -> i32 {
        s.chars()
            .enumerate()
            .fold(HashMap::new(), |mut m, (index, ch)| {
                m.entry(ch)
                    .and_modify(|(_, i): &mut (usize, i32)| *i += 1)
                    .or_insert((index, 1));
                m
            })
            .values()
            .fold(-1, |ans, &(index, count)| {
                if count == 1 && (ans == -1 || (index as i32) < ans) {
                    index as i32
                } else {
                    ans
                }
            })
    }
}