解题思路
这是一个字符去重问题,需要保持字符的原始顺序。
关键点:
- 使用集合记录已出现的字符
- 保持字符的原始顺序
- 处理多组输入
- 区分大小写
算法步骤:
- 读取输入字符串
- 使用集合去重
- 按原顺序输出
代码
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string removeDuplicates(const string& str) {
string result;
unordered_set<char> seen;
for (char c : str) {
if (seen.find(c) == seen.end()) {
result += c;
seen.insert(c);
}
}
return result;
}
};
int main() {
string line;
Solution solution;
while (getline(cin, line)) {
cout << solution.removeDuplicates(line) << endl;
}
return 0;
}
import java.util.*;
public class Main {
static class Solution {
public String removeDuplicates(String str) {
StringBuilder result = new StringBuilder();
Set<Character> seen = new HashSet<>();
for (char c : str.toCharArray()) {
if (!seen.contains(c)) {
result.append(c);
seen.add(c);
}
}
return result.toString();
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Solution solution = new Solution();
while (sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(solution.removeDuplicates(line));
}
sc.close();
}
}
class Solution:
def remove_duplicates(self, s: str) -> str:
seen = set()
result = []
for c in s:
if c not in seen:
result.append(c)
seen.add(c)
return ''.join(result)
if __name__ == "__main__":
solution = Solution()
while True:
try:
line = input().strip()
print(solution.remove_duplicates(line))
except EOFError:
break
算法及复杂度
- 算法:集合去重
- 时间复杂度:,其中 是字符串长度
- 空间复杂度:,其中 是不重复字符的数量