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

    刚开始还在想双指针,完全没必要。然后最土的可以扫两遍O(n),用一个数组记录出现次数。然后想到如果数组里记录出现的位置,可以只扫一遍O(n),第二遍扫字符集就行了。

    #include <iostream>
    #include <string>
    using namespace std;
     
    #define INF 1<<30
    int main()
    {
        string s;
        while (cin >> s)
        {
            int len = s.length();
            if (len == 0)
            {
                cout << "-1" << endl;
                continue;
            }
            int count[26];
            for (int i = 0; i < 26; i++)
            {
                count[i] = -1;
            }
            for (int i = 0; i < len; i++)
            {
                if (count[s[i]-'A'] == -1)
                {
                    count[s[i]-'A'] = i; // save the first position
                }
                else
                {
                    count[s[i]-'A'] = INF;
                }
            }
            int min = INF;
            for (int i = 0; i < 26; i++)
            {
                if (min > count[i] && count[i] != -1) min = count[i];
            }
            if (min != INF) cout << min << endl;
            else cout << -1 << endl;
        }
        return 0;
    }
    

      

  • 相关阅读:
    kvm virtio
    GPU 线程块/线程束
    ubuntu source
    React
    分布式系统
    honpeyhonepy
    css是干什么的
    bootstrap中的横的列
    数据安全之 alert logic
    viewset的使用的方法
  • 原文地址:https://www.cnblogs.com/lautsie/p/3404468.html
Copyright © 2011-2022 走看看