2018-08-16 计算字符串中相邻位置相同字符的个数(1)

2018-08-16  本文已影响0人  放开那只三级头

牛客上的网易游戏研发面经上看到的题,题目描述我直接复制黏贴过来:
1)单字符串压缩 :

输入:ABBBCCD , 输出AB3C2D

思路:用hash_map存储每个字符对应的个数(本人大一刚学编程,复杂度什么的没怎么考虑= =)
tips: C++使用hash_map时命名空间为__gnu_cxx,须加上,否则无法通过编译。

代码如下

#include <iostream>
#include <hash_map>
#include <string>
using namespace std;


//输入:ABBBCCD , 输出AB3C2D


int main()
{
    std::string str;
    __gnu_cxx::hash_map<char,int> map1;
    cin>>str;
    for (int i=0;i<str.length();i++){
        if (i==0) map1[str[0]]=1;
        if (i>0){
            if (str[i]==str[i-1]){map1[str[i]]+=1;}
            else map1[str[i]]=1;
        }
    }
    __gnu_cxx::hash_map<char, int>::iterator iter;
    iter = map1.begin();
    while(iter != map1.end()) {
        if (iter->second==1) {cout<<iter->first;}
        else{
            cout << iter->first << iter->second;
        }
        iter++;
    }

}

不知道有没有复杂度更低的方法?

上一篇下一篇

猜你喜欢

热点阅读