现有一台2G内存4核CPU的电脑,尽可能快速的找出一个3.7亿的字符中 第一个不重复的字符,用Java代码实现
时间: 2023-05-27 12:06:48 浏览: 42
以下是一个基于哈希表的算法,可以在较短的时间内找到第一个不重复的字符:
```java
import java.util.HashMap;
public class FirstNonRepeatedChar {
public static char findFirstNonRepeatedChar(String str) {
HashMap<Character, Integer> charCount = new HashMap<Character, Integer>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (charCount.containsKey(c)) {
charCount.put(c, charCount.get(c) + 1);
} else {
charCount.put(c, 1);
}
}
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (charCount.get(c) == 1) {
return c;
}
}
return '\0';
}
public static void main(String[] args) {
String str = "abacdbecefedgfhgihijhiklmnlnmomopqrqrsst";
char firstNonRepeatedChar = findFirstNonRepeatedChar(str);
System.out.println("The first non-repeated character is: " + firstNonRepeatedChar);
}
}
```
这个算法的时间复杂度为O(N),其中N是字符总数。在3.7亿的字符中查找第一个不重复的字符可能需要一些时间,但是在一台2G内存4核CPU的电脑上应该可以处理得很快。如果需要加快处理速度,可以考虑使用多线程或分布式处理。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)