簡體   English   中英

如何將char元素數組移到左邊

[英]How to shift array of char elements to left

我有一個字符數組。 我應該刪除任何重復的字符。 我將字符串元素與字母數組進行了比較。 還有另一個數組充當任何duplictae字母表的計數器。 如果已經多次找到任何字符,我應該刪除重復的字符並將元素移到左邊。 下面是代碼。 我在評論的行中收到錯誤。 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

注意:它只返回一次字符,並且新剪裁的字符串中不會考慮字母表中沒有的字符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM