編程題_刪除公共字符—Java

輸入兩個字符串,從第一字符串中刪除第二個字符串中所有的字符。例如,輸入”They are students.”和”aeiou”,則刪除之後的第一個字符串變成”Thy r stdnts.”

輸入描述:

每個測試輸入包含2個字符串

輸出描述:

輸出刪除後的字符串

示例1

輸入

They are students. aeiou

輸出

Thy r stdnts.

解法一:暴力解決

遍歷第一個字符串並對比當前字符是否在第二個字符串中,如果在,將其刪除,如果不再,就留下

import java.util.* ;
public class Main
{
    public static String removeAll (String str, char a)
    {
        char[] arr = str.toCharArray();
        StringBuffer sb = new StringBuffer();
        for (int i=0; i<str.length(); i++)
        {
            if (arr[i] != a)
            {
                sb.append(arr[i]);
            }
        }
        return sb.toString();
    }

    public static void removeAll2(String str1, String str2)
    {
        char[] arrs = str2.toCharArray();
        for (int i=0; i<arrs.length; i++)
        {
            if (str1.contains(arrs[i]+""))
            {
                str1 = removeAll(str1, arrs[i]);
            }
        }
        System.out.println(str1);
    }

    public static void main(String[] args)
    {
        Scanner s = new Scanner (System.in);
        while (s.hasNext())
        {
            String str1 = s.next();
            String str2 = s.next();
            removeAll2(str1, str2);
        }
    }
}

這種方法雖然可以實現題目要求,但是明顯時間複雜度非常大,因此可以使用哈希表的方式將其優化

具體方法是:通過hash表的思想,先記錄要被刪除的元素,然後再將其刪除,時間複雜度爲O(m+n),空間複雜度爲O(256)

import java.util.Scanner;

/**
 * 使用哈希表的方式,先算出要刪除的字母出現的次數,在將其刪除
 * 時間複雜度爲O(m+n)
 * 空間複雜度爲O(256)
 */
public class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        while (s.hasNext())
        {
            String source = s.nextLine();
            String del = s.nextLine();
            removeAll(source, del);
        }
    }

    private static void removeAll(String source, String del)
    {
        int[] chars = new int[256];
        for (int i=0; i<del.length(); i++)
        {
            chars[del.charAt(i)] ++; // 對應位置的數字加一
        }
        char[] ret = new char[source.length()];
        int index = 0;
        for (int i=0; i<source.length(); i++)
        {
            if (chars[source.charAt(i)] == 0)
            {
                ret[index++] = source.charAt(i);
            }
        }
        System.out.println(new String(ret, 0, index));
    }
}

解法三:通過正則表達式的方式,代碼如下:

import java.util.Scanner;

/**
 * 使用正則表達式解題
 */
public class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        while (s.hasNext())
        {
            String s1 = s.nextLine();
            String s2 = s.nextLine();
            String del = "["+s2+"]"; // 字符串類型的正則表達式
            System.out.println(s1.replaceAll(del, ""));
        }
    }
}

運行結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章