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
  • 相关阅读:
    第一个只出现一次的字符字符(python)
    丑数(python)
    as3.0对图片进行不规则切割源代码实例
    AS3代码生成xml方法
    获取fla 总场景个数
    微信小程序开发工具下载
    actionscript(flash)和java后台的数据交互
    截取位图的某一部分 (像素)
    拷贝颜色通道
    将文本转换为位图
  • 原文地址:https://www.cnblogs.com/wangxiaoyong/p/8659376.html
Copyright © 2011-2022 走看看