解题思路
-
题目要求:
- 找出字符串中第一个只出现一次的字符
- 如果不存在输出-1
- 字符串长度不超过1000
-
实现思路:
- 使用哈希表记录每个字符出现的次数
- 再次遍历字符串,找到第一个出现次数为1的字符
- 如果不存在这样的字符,返回-1
-
优化方案:
- 可以使用数组代替哈希表(因为字符集有限)
- 使用两次遍历确保保持字符的原始顺序
代码
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main() {
string str;
while (cin >> str) {
// 统计每个字符出现的次数
unordered_map<char, int> count;
for (char c : str) {
count[c]++;
}
// 找第一个只出现一次的字符
char result = '\0';
for (char c : str) {
if (count[c] == 1) {
result = c;
break;
}
}
if (result == '\0') {
cout << -1 << endl;
} else {
cout << result << endl;
}
}
return 0;
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String str = sc.next();
// 统计每个字符出现的次数
Map<Character, Integer> count = new HashMap<>();
for (char c : str.toCharArray()) {
count.put(c, count.getOrDefault(c, 0) + 1);
}
// 找第一个只出现一次的字符
char result = '\0';
for (char c : str.toCharArray()) {
if (count.get(c) == 1) {
result = c;
break;
}
}
if (result == '\0') {
System.out.println(-1);
} else {
System.out.println(result);
}
}
}
}
while True:
try:
s = input()
# 统计每个字符出现的次数
count = {}
for c in s:
count[c] = count.get(c, 0) + 1
# 找第一个只出现一次的字符
result = None
for c in s:
if count[c] == 1:
result = c
break
print(result if result is not None else -1)
except EOFError:
break
算法及复杂度
- 算法:哈希表统计
- 时间复杂度:
- 需要两次遍历字符串
- 空间复杂度:
-
为字符集大小,本题中
最大为所有可能的字符数