zoukankan      html  css  js  c++  java
  • 剑指Offer-33.第一个只出现一次的字符(C++/Java)

    题目:

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

    分析:

    遍历字符串,利用Hashmap将每一个字符出现的值存储起来,然后再遍历字符串,返回第一个字符值为1的索引即可。

    程序:

    C++

    class Solution {
    public:
        int FirstNotRepeatingChar(string str) {
            for(int i = 0; i < str.size(); ++i){
                m[str[i]]++;
            }
            for(int i = 0; i < str.size(); ++i){
                if(m[str[i]] == 1)
                    return i;
            }
            return -1;
        }
    private:
        map<char, int> m;
    };

    Java

    import java.util.*;
    public class Solution {
        public int FirstNotRepeatingChar(String str) {
            for(int i = 0; i < str.length(); ++i) {
                if(map.containsKey(str.charAt(i))){
                    int count = map.get(str.charAt(i));
                    map.put(str.charAt(i), ++count);
                }
                else {
                    map.put(str.charAt(i), 1);
                }
            }
            for(int i = 0; i < str.length(); ++i) {
                if(map.get(str.charAt(i)) == 1) {
                    return i;
                }
            }
            return -1;
        }
        private HashMap<Character, Integer> map = new HashMap<>();
    }
  • 相关阅读:
    54.Spiral Matrix
    53.Maximum Subarray
    基础数据类型包装类
    sqlacodegen逆向数据库
    第四章、常用模块
    第三章、函数编程
    第一章
    第一章 Python基础
    Centos7.0升级python 2.x到3.x
    time
  • 原文地址:https://www.cnblogs.com/silentteller/p/11980439.html
Copyright © 2011-2022 走看看