我有一个字符数组。我应该删除所有重复的字符。我对字符串元素与字母数组进行了比较。还有另一个数组可以充当任何重复字母表的计数器。如果多次找到任何字符,我应该删除重复的字符并将元素向左移动。下面是代码。我在评论行遇到错误。 Java 需要赋值的左侧是变量。你能帮我吗?
import java.util.ArrayList;
import java.util.Scanner;
public class removeduplicate {
public static void main (String args[])
{
Scanner s=new Scanner(System.in);
String str="abbsded";
String myChars="abcdefghijklmnopqrstuvwxyz";
int[] myCounter=new int[26];
for (int i=0; i<str.length(); i++)
{
for(int j=0; j<myChars.length(); j++)
{
if(str.charAt(i)==myChars.charAt(j))
{
myCounter[j]++;
if (myCounter[j]>1)
{
System.out.println("duplication found in "+ str.charAt(i));
for(int h=i; h<str.length();h++)
{
//this line does not work.
str.charAt(h)=str.charAt(h-1);
}
}
}
}
}//end for
}
}
最佳答案
您可以使用 HashMap 来跟踪您在实现过程中遇到的字符。然后每次看到字母表中的字符时就递增。仅当之前未见过该字符时才将字母添加到返回的字符串中。
public static String removeDuplicates(String input)
{
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
input = input.toUpperCase();
HashMap<Character, Integer> charData = new HashMap<>();
//create the map to store counts of all the chars seen
for(int i = 0; i < alphabet.length(); i++)
charData.put(alphabet.charAt(i), 0);
String cleanedInput = "";
for(int index = 0; index < input.length(); index++)
{
char letter = input.charAt(index);
if(charData.containsKey(letter))
{
charData.put(letter, charData.get(letter) + 1);
//if count is 1 then its the first time we have seen it
if(charData.get(letter) == 1)
{
cleanedInput += letter;
}
}
}
return cleanedInput.toLowerCase();
}
调用示例
public static void main(String[] args) {
System.out.println(removeDuplicates("abbsded"));
System.out.println(removeDuplicates("abbsded!!!"));
System.out.println(removeDuplicates("hahahahahahahahahah"));
}//main method
输出
absde
absde
ha
注意:它只返回一次字符,并且在新的修剪字符串中不会考虑字母表之外的字符。
关于java - 如何将 char 元素数组向左移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42012225/