有没有更好的方法呢?我想从一个数组中减去另一个数组中的字符

时间:2014-09-14 06:41:40

标签: java arrays time-complexity

所以我在这里基本上要做的是从数组中取出'S''P''O''R''T'等字符,其中包含来自'A'的所有字母... 'Z'这段代码工作正常,但我想知道是否有更好的方法来做...更简化的版本左右..我会很感激答案,只涉及数组n不列表或哈希!

String key = "SPORT";
char [] keys = key.toCharArray();

String alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char [] alpha = alphabets.toCharArray();
int len = alpha.length;
int keylen = keys.length;
System.out.println(len);
int new_len = (alpha.length) - keylen;
char [] newalpha = new char [new_len];
for (int j = 0 ; j < keys.length ; j++) {
    for (int i = 0 ; i < len ; i++) {
        if (alpha[i] == keys[j]) {
            alpha[i] = '@';
        }
    }
}
int k = 0;
for (int i = 0 ; i < len ; i++) {
    if (alpha[i] != '@') {
        newalpha[k] = alpha[i];
        k++;
    }
}
for (int i = 0 ; i < newalpha.length ; i++) {
    System.out.println(newalpha[i]);
}

2 个答案:

答案 0 :(得分:1)

在Java 8中

<强>代码

    String alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    List<String> list = Arrays.asList(alphabets.split(""));

    List<String> result = list.stream().filter(s -> !(s.equals("S") || s.equals("P") || s.equals("O")
            || s.equals("R") || s.equals("T"))).collect(Collectors.toList());
    System.out.println("The list of letters after after extractison S P O R T are ");
    result.stream().forEach(s -> System.out.print(" " + s));
    System.out.println("");
    System.out.println("The number of letters after extractison S P O R T is " + result.stream().count());

<强>输出

The list of letters after after extractison S P O R T are 
 A B C D E F G H I J K L M N Q U V W X Y Z
The number of letters after extractison S P O R T is 21

解释

据我所知,Java 8中的lambda只适用于List,所以我使用Arrays.asList将String转换为列表。接下来,我使用filter作为if语句来查看列表并忽略S P O RT并将其收集为List命名结果。最后,我使用for loop的新形式打印列表,并显示提取这些字母后我们有多少个字母。

清理版本

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;


public class TakeOutChars {

  public static void main(String[] args) {
    String alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    List<String> list = Arrays.asList(alphabets.split(""));
    System.out.println(filterSPORT(list, ignoreSPORT()));
    System.out.println(filterSPORT(list, ignoreSPORT()).stream().count());
}

public static Predicate ignoreSPORT() {
return s -> !(s.equals("S") || s.equals("P") || s.equals("O")
            || s.equals("R") || s.equals("T"));

  }

public static List<String> filterSPORT(List list, Predicate predicate) {
    return (List<String>) list.stream().filter( predicate ).collect(Collectors.toList());
}   
  }

清理版本的输出

[A, B, C, D, E, F, G, H, I, J, K, L, M, N, Q, U, V, W, X, Y, Z]
21

答案 1 :(得分:0)

您可以使用以下提到的代码:

String key = "SPORT";
key  = key.toUpperCase();
char[] keys = key.toCharArray();

String alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

for (char c : keys) {
    alphabets = alphabets.replace(c, '@');
}

alphabets = alphabets.replaceAll("@", "");
System.out.println(alphabets);