簡體   English   中英

Java 數組字符串比較

[英]Java Array String Compare

大家好,我正在嘗試比較一個數組,我想打印位置 [0] 和 [1] 之間的共同字母

例如,在數組 [0] 中,我有類似 a[0]=aokk 的內容,而在另一個位置,我有一個說 a[1]=ok;

我希望問題只打印位置 0 中的字母,而且我正在做的是

for (int j = 0; j < a[0].length(); j++) {
    for (int i = 0; i < a[1].length(); i++) {
        if (a[0].charAt(i) == b[1].charAt(j)) {
            common += a[0].charAt(i);
        }
    }
}

但是當它應該是“ok”時,我得到了一個輸出“okk”,因為 K 在位置 [0] 只有一次

該算法的問題在於您正在比較兩個不同長度的字符串。 在這種情況下,長度較短的字符串比另一個字符串更早完成循環,因此較短的字符串的索引保留在最后一個元素,即“k”。 另一個字符串的循環仍在繼續,當它到達字母“k”時,您的 if 條件為真(因為“k”==“k”),這就是為什么您將擁有雙倍 k。

嘗試從 common 中刪除重復項:

List<Character> list = new ArrayList<Character>();
for (char ch : common.toCharArray()) {
            list.add(ch);
}
return new HashSet<>(list).toString();
public class PrintCommonLetters {

    public static void main(String[] args) {

        // Strings in array for comparison
        String[] array = {"ok","aokk", "ko"};

        for(int i = 0; i < array.length - 1; i++)
        {
            for(int j = i + 1; j <= array.length - 1; j++)
            {   
                // Compare which string is longer
                if(array[i].length() > array[j].length())
                {
                    // Found substring array[j] in array[i]
                    if(array[i].contains(array[j]))
                        System.out.println(array[j]);
                }
                else
                {
                    // Found substring array[i] in array[j]
                    if(array[j].contains(array[i]))
                        System.out.println(array[i]);
                }               
            }
        }
    }
}

如果排序不重要,那么您可以使用以下代碼。 您可以對兩個數組進行排序,然后更改合並排序以進行字符串中常見的比較。

public static String commonInArray(char[] char1, char[] char2) {
    int i = 0, j = 0;

    String common = "";

    while(i < char1.length) {
        if(char1[i] == char2[j]) {
            common += char1[i];
            i++;
            j++;
        } else if(char1[i] > char2[j]) {
            j++;
        } else {
            i++;
        }
    }

    return common;
} 

public static void main (String[] args) {
    // Strings in array for comparison
    String[] array = {"bitter","letter"};

    char[] char1 = array[0].toCharArray();
    Arrays.sort(char1);

    char[] char2 = array[1].toCharArray();
    Arrays.sort(char2);

    String common;

    if(char1.length > char2.length) {
        common = commonInArray(char1, char2);
    } else {
        common = commonInArray(char2, char1);
    }

    System.out.println(common);
}

替代解決方案:

1) 將第一個字符串存儲在鏈表中

2) 遍歷第二個字符串

3) 從鏈表中刪除公共元素

    String[] a = {"aokk", "ok"};
    String common = "";

    LinkedList<Character> store = new LinkedList<Character>();

    for(int i = 0; i < a[0].length(); i++) {
        store.add(a[0].charAt(i));
    }

    for (int i = 0; i < a[1].length(); i++) {
        if(store.contains(a[1].charAt(i))) {
            common += a[1].charAt(i);
            store.remove(store.indexOf(a[1].charAt(i)));
        }
    }

    System.out.println(common);

這是您需要的:

import java.util.ArrayList;
import java.util.List;

class Solution{
    public static void main(String args[]){
        String arr[] = {"aokk","ok"};
        List<Integer> index = new ArrayList<Integer>();
        for(int i=0;i<arr[0].length();i++){
            for(int j=0;j<arr[1].length();j++){
                if(arr[0].charAt(i)==arr[1].charAt(j) && index.contains(j)==false){
                    System.out.print(arr[0].charAt(i)); //print if it matches
                    index.add(j);//add index to list so it won't count again
                    break;
                }
            }
        }
    }
}

嘗試這個 :

1.Assuming in your case,that in String array , a[0] has maximum length
2.Of course, you can get the maximum length from the string array you can choose the max length and you can modify the length and do according to your requirement.                                
3. For now, check the following :

public static void main(String[] args) 
{

String a[]={"aokk","ok"};
String common = "";
 for(int i=0;i < a[1].length();i++)
 {
  for(int j=0; j<a[0].length();j++) 
  {
    if(a[1].charAt(i) == a[0].charAt(j) && common.indexOf(a[0].charAt(j))<0)
    {
       common = common + a[0].charAt(j);
    }
  }
 }
  System.out.println(common);
}

已經有大量的解決方案,每個都有自己的優點和缺點。 我會提出我的建議。 我假設字母的順序並不重要,但如果一個字母在每個字符串中出現兩次,它也必須在結果中出現兩次。

/** @return chars common to a[0] and a[1] */
public static String commonChars(String[] a) {
    int[] charCounts = new int[256];
    for (int index = 0; index < a[0].length(); index++) {
        charCounts[a[0].charAt(index)]++;
    }
    StringBuilder result = new StringBuilder(a[0].length());
    for (int index = 0; index < a[1].length(); index++) {
        if (charCounts[a[1].charAt(index)] > 0) {
            result.append(a[1].charAt(index));
            charCounts[a[1].charAt(index)]--;
        }
    }
    return result.toString();
}

我自己判斷的優勢:考慮到一個字母可能出現兩次(如按鈕和黃油,或字母和苦味)。 相當有效(這可能無關緊要)。 萬一重要,字母通常以與a[1]相同的順序出現。

我知道的弱點:如果任一字符串包含超出 Latin-1 范圍(0 到 255)或a小於 2 的字符,則會出現ArrayIndexOutOfBoundsException

暫無
暫無

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

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