题解 | #找出字符串中第一个只出现一次的字符#
找出字符串中第一个只出现一次的字符
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")
格力公司福利 459人发布
查看8道真题和解析
