[英]how to remove same characters from a huge string using method in java
I have a string of 10^1000 characters.where we cant run a loop to check one by one..then what should i do? 我有一个10 ^ 1000个字符的字符串。在这里我们无法运行循环来逐个检查..那我该怎么办?
i do like 我喜欢
public class test {
public static void main(String[] args) {
String input = new String("abbc");
String output = new String();
for (int i = 0; i < input.length(); i++) {
for (int j = 0; j < output.length(); j++) {
if (input.charAt(i) != output.charAt(j)) {
output = output + input.charAt(i);
}
}
}
System.out.println(output);
}
}
I do it in this way to remove the all duplicate character from a string .but it is not efficient when the input.length() is too large. 我这样做是从字符串中删除所有重复的字符。但是当input.length()太大时,效率不高。
You can try to convert the string to an array of char, and store it in a LinkedHashSet. 您可以尝试将字符串转换为char数组,并将其存储在LinkedHashSet中。 That will preserve your ordering, and remove duplicates
这样可以保留您的订购,并删除重复的商品
char[] chars = string.toCharArray();
Set<Character> charSet = new LinkedHashSet<Character>();
for (char c : chars) {
charSet.add(c);
}
StringBuilder sb = new StringBuilder();
for (Character character : charSet) {
sb.append(character);
}
System.out.println(sb.toString());
If your String has separator I think that you could use a Set. 如果您的字符串具有分隔符,我认为您可以使用Set。
Set<String> set = new HashSet<String>(Arrays.asList(text.split(" ")));
Or in java 8: 或在Java 8中:
Set<String> set = Arrays.stream(text.split(" ")).collect(Collectors.toSet());
You could maintain a set of characters ( Set<Character>
) you already did encounter for 0 .. (i-1). 您可以维护一组字符(
Set<Character>
),您已经遇到了0 ..(i-1)。
As this reeks of homework I leave it to that. 由于这是家庭作业的琐事,我将其留给了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.