zoukankan      html  css  js  c++  java
  • leetCode 题解之字符串中第一个不重复出现的字符

    1、题目描述

           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。

    2、问题分析

         题目可以使用 hash 的手段来解决,首先将每个字符串中的字符放入一个map 容器中。在map 容器中记录每个字符出现的次数。最后找出第一个出现次数为1 的数。

       C++ 中, 关联容器有两大类,其一是 ,map  ,其二是 set 。map  可以定义为 unordered_map<key,value>,key表示键,value 表示 值,使用 key  来索引 value 。在本题中,

         key 是每个输入字符串中每个 字符,value 则是该字符在输入字符串中的出现次数。

         关联容器定义如下  :

                   

    1 unordered_map<char,int> m;

    3、代码

     1 int firstUniqChar(string s) {
     2         // 使用 hash 表将string 中的每一个字符出现次数统计,需要使用无序map 容器
     3         
     4     unordered_map<char , int> m;
     5  
     6     for( const auto &c : s )
     7         ++m[c];
     8 
     9     for( int i = 0; i < s.size(); i++ )
    10     {
    11         if( m[s[i]]  == 1 )
    12             return i;
    13     }
    14         
    15 
    16      return -1;
    17     }
    pp
  • 相关阅读:
    [转]如何得到Oracle跟踪文件的文件名
    [转]一张图即可说明常规B/S架构
    [原]SQL中获得序列的方法
    [摘]sql走索引,怎么始终有物理读?
    CSS3太强悍了
    [原]简单分析《趣味题》中的SQL
    SendArp获取MAC地址
    nbtstat a ip 获取MAC地址等
    C#定时器的使用
    C#调用WMI关机示例
  • 原文地址:https://www.cnblogs.com/wangxiaoyong/p/8659376.html
Copyright © 2011-2022 走看看