zoukankan      html  css  js  c++  java
  • 剑指offer-第一个只出现一次的字符

    题目描述

    在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).

    思路:

    1.先统计每个字母出现的次数,保存在arr数组中

    2.找到只出现一次的字母,将其位置保存在place数组中

    3.找到place数组中位置最小的那个,即为正确答案

    4.否则则返回-1,(题目中忘写了,但是也通过了)

    class Solution {
    public:
        int FirstNotRepeatingChar(string str) {
            int len = str.length();
            if(len==0)  return -1;
            vector<int> arr(58,0);   //用来存放每个字母出现次数
            vector<int> place(58,10001); //用来存放只出现一次的字母所在字符串位置
            int temp;
            for(int i=0;i<len;i++)
            {
                temp = str[i];
                arr[temp-65]++;
            }
            
            for(int i=0;i<58;i++)
            {
                if(arr[i]==1) //只出现一次
                {
                    for(int j=0;j<len;j++)
                    {
                        temp = str[j];
                        if(temp-65==i)
                        {
                            place[i] = j;
                            break;
                        }
                    }
                }
            }
            //对place进行排查
            int min = 10001; 
            for(int i=0;i<58;i++)
            {
                if(place[i]<min)
                {
                    min = place[i]; 
                }
            }
            return min;
        }
    };
  • 相关阅读:
    clean code
    jenkins
    获取目录下的文件名称
    bootstrap-select 下拉互斥
    supervisord
    正则表达式
    Docker
    git
    goland工具
    小程序 swiper 轮播图滚动图片 + 视频
  • 原文地址:https://www.cnblogs.com/loyolh/p/12346903.html
Copyright © 2011-2022 走看看