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

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

     1 #include<iostream>
     2 #include<vector>
     3 #include<map>
     4 #include<string>
     5 #include<unordered_map>
     6 using namespace std;
     7 
     8 int main()
     9 {
    10     unordered_map<char, int> m;
    11     string str="";
    12     cin>>str;
    13     int len = str.size();
    14     //cout << len << endl;
    15     unordered_map<char, int>::iterator ite;
    16     for (int i = 0; i < len; i++)
    17     {
    18         m.insert(pair<char, int>(str[i], 0));
    19     }
    20     /*for (ite = m.begin(); ite != m.end(); ++ite)
    21     {
    22         cout << ite->first << " " << ite->second << endl;
    23     }*/
    24     for (int i = 0; i < len; i++)
    25     {
    26         m[str[i]]++;
    27     }
    28     //for (ite = m.begin(); ite != m.end(); ++ite)
    29     //{
    30     //    cout << ite->first << " " << ite->second << endl;
    31     //}
    32     char c;
    33     for (int i = 0; i <m.size(); i++)
    34     {
    35         if (m[str[i]] == 1)
    36             c = str[i];
    37     }
    38 //    cout << c << endl;
    39     int x;
    40     for (int i = 0; i < len; i++)
    41     {
    42         if (c == str[i])
    43             x = i;
    44     }
    45     cout << x+1 << endl;
    46     system("pause");
    47     return 0;
    48 }

    上面的是我写的,自己的ide可以过去,没有提交,看到一个算法,思路清晰,也比较简单,放在下面。

     1 #include<iostream>
     2 #include<vector>
     3 #include<map>
     4 #include<string>
     5 #include<unordered_map>
     6 using namespace std;
     7 
     8 int main()
     9 {
    10     string str;
    11     cin >> str;
    12     int x;
    13     for (int i = 0; i < str.size(); i++)
    14     {
    15         if (str.find(str[i]) == str.rfind(str[i]))
    16         {
    17             x = i;
    18             break;
    19         }
    20     }
    21     cout << x + 1 << endl;
    22     system("pause");
    23     return 0;
    24 }
  • 相关阅读:
    Linux常用命令
    全文搜索服务器solr
    非关系型数据库之redis
    springMVC流程
    浅谈spring框架的控制反转和依赖注入
    Java基础之数组
    Java基础之方法
    跨域访问接口,传递参数
    Centos 6无法使用yum
    内网穿透工具:钉钉HTTP内网穿透使用与讲解
  • 原文地址:https://www.cnblogs.com/wujufengyun/p/6927786.html
Copyright © 2011-2022 走看看