题解 | #找出字符串中第一个只出现一次的字符#

找出字符串中第一个只出现一次的字符

https://www.nowcoder.com/practice/e896d0f82f1246a3aa7b232ce38029d4

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

class FirstCharAppearOnce {
  private:
    string s;

  public:
    //构造函数
    FirstCharAppearOnce(const string s);

    //析构函数
    ~FirstCharAppearOnce();

    //找出字符串中第一个只出现一次的字符
    const char search(void)const;

    //输出
    void print(void)const;
};

FirstCharAppearOnce::FirstCharAppearOnce(const string s) {
    this->s = s;
    return;
}

FirstCharAppearOnce::~FirstCharAppearOnce() {
}

const char FirstCharAppearOnce::search(void) const {
    //遍历字符串
    for (int i = 0; i < this->s.size(); i++) {

        //寻找相同字符
        int j = 0;
        for (; j < this->s.size(); j++) {
            if (this->s[i] == this->s[j]) {

                //同一个字符不算相同字符
                if (i == j)
                    continue;
                break;
            }
        }

        //j == this->s.size()说明本次循环未触发过break,即未遇到过相同字符
        if (j == this->s.size())
            return this->s[i];
    }
    return 0;
}

void FirstCharAppearOnce::print(void) const {
    char ch = this->search();
    if (ch) {
        cout << ch << endl;
        return;
    } else {
        cout << "-1" << endl;
        return;
    }
}

int main() {
    string a;
    while (cin >> a) { // 注意 while 处理多个 case
        FirstCharAppearOnce(a).print();
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

01-30 22:03
门头沟学院 Java
用微笑面对困难:我滴妈,【俩月】【实习】【主管】仨debuff吃满了,独立设计开发的项目写了绝大占比的运营板块,你独立开发,那维护、问题复盘、日志更新、bug、策划书全是自己整的? 不建议写那么大,可以从小出发更容易
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务