zoukankan      html  css  js  c++  java
  • LC 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.

    参考答案

     1 class Solution {
     2 public:
     3     int firstUniqChar(string s) {
     4 
     5         int count[26] = {0};
     6         for(char c:s){
     7             count[c-'a']++;
     8         }
     9         for(size_t i = 0; i<s.size();i++){
    10             if(count[s[i] - 'a'] == 1) return i;
    11         }
    12         return -1;
    13         
    14         /*
    15         unordered_map<char,int> map;
    16         int min = 0;
    17         
    18         for(size_t i = 0 ; i < s.length();++i){
    19             if(map.count(s[i])>0){
    20                 map[s[i]] = -1;
    21             }else{
    22                 map[s[i]] = i;
    23             }
    24         }
    25         for(size_t i = 0 ; i < s.length();++i){
    26             if(map[s[i]] != -1){
    27                 return map[s[i]];
    28             }
    29         }
    30         return -1;*/
    31         }
    32 };

    补充说明

    第一次自己想出了accepted的答案,虽然和第一名的大佬差了很多,但是感觉还是很兴奋的。

    答案中,使用了 count [ c - 'a' ] ,巧妙地将字母表示成为index。

  • 相关阅读:
    js Array的方法及属性总结
    js 继承
    js 判断数据类型
    序列化和反序列化
    express 常用方法和插件
    node 常用的对象
    node.js 守护进程
    CentOS7安装Python3.8.1和ansible
    MAC终端终极美化方案
    Linux之top命令详解
  • 原文地址:https://www.cnblogs.com/kykai/p/11616614.html
Copyright © 2011-2022 走看看