zoukankan      html  css  js  c++  java
  • 34第一个只出现一次的字符

    题目描述

    在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置

    思路:
    用数组建一个哈希表,key 是字符,val是次数。
    第一次遍历,统计次数
    第二次遍历,把次数为1的下标输出。

     1 public class Solution {
     2     public int FirstNotRepeatingChar(String str) {
     3         int[] cnt =  new int[256];
     4         if(str.length()<0) return -1;
     5         for(int i = 0;i<str.length();i++){
     6             cnt[str.charAt(i)-'A']++;
     7         }
     8         for(int i = 0;i<str.length();i++){
     9             if(cnt[str.charAt(i)-'A']==1)
    10                 return i;
    11         }
    12         return -1;
    13     }
    14 }

    c++:20180725

     1 class Solution {
     2 public:
     3     int FirstNotRepeatingChar(string str) {
     4         std::map<char, int> mymap;
     5         for(int i = 0;i<str.size();i++)
     6             mymap[str[i]]++;
     7         
     8         for(int i =0;i<str.size();i++)
     9             if(mymap[str[i]]==1)
    10                 return i;
    11     return -1;        
    12     }
    13     
    14 };
  • 相关阅读:
    dp的冗余(选数类)
    noip2016自测报告
    dalao高精
    二叉苹果树
    最长上升子序列加强版
    Above the Median
    树状数组学习笔记
    Java委托机制
    Java集合
    Java异常
  • 原文地址:https://www.cnblogs.com/zle1992/p/8158146.html
Copyright © 2011-2022 走看看