如何添加字符串以设置字符不重复

时间:2017-03-19 09:47:01

标签: java set

我是Java中的新手。我有一个问题,我不知道如何做到这一点: 我需要在我的Set中添加字符串,字符不会重新映射。 例如string" ABC"将添加到我的Set,但字符串" ABCC"不会添加,因为包含double" C"。

        import java.util.HashSet;

import java.util.Set;

public static void main(String[] args) {
    Set<String> napisy = new HashSet<>();

}

}

9 个答案:

答案 0 :(得分:1)

首先尝试检查String是否有重复项,如果没有,请将其添加到Set

Set<String> s = new HashSet<>();
String a = "Abc";
if(checkUnique(a)){
    s.add(a);
}

checkUnique

的实施
public static boolean checkUnique(String a){
    Set<Character> set = new HashSet<>();
    for(char c : a.toCharArray()){
        if(set.contains(c))
            return false;
        set.add(c);
    }
    return true;
}

答案 1 :(得分:1)

一种可能的方法是迭代每个字符串,并为每一个字符串迭代它们的每个字符串。
在这个内循环中,您可以使用Set存储当前String的每个遇到的字符,因此只要要添加的字符已经在集合中,您就会停止迭代而不是; t添加字符串。否则,您添加String

以下是代码:

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SetWithNotCharDuplicated {

    public static void main(String[] args) {

        List<String> inputStrings = Arrays.asList("ABC", "ABCC", "ABD", "AABD");
        Set<String> values = findStringsWithNoDupplicatedCharInsideIt(inputStrings);
        System.out.println(values);
    }

    private static Set<String> findStringsWithNoDupplicatedCharInsideIt(List<String> inputStrings) {
        Set<String> values = new HashSet<>();

        for (String string : inputStrings) {
            Set<Character> encounteredChars = new HashSet<Character>();

            boolean mustAdd = true;

            for (char c : string.toCharArray()) {

                // we skip the current String if already contained
                if (encounteredChars.contains(c)) {
                    mustAdd = false;
                    break;
                }
                encounteredChars.add(c);
            }

            if (mustAdd) {
                values.add(string);
            }
        }
        return values;
    }
}

输出:

  

[ABC,ABD]

答案 2 :(得分:1)

我认为下面的实施应该是对上述问题的正确和快速回答。

考虑字符串str =“abdg @ d @ aa%6%” 此字符串不应添加到包含的集合中(3次,2次@和2次%)

Step 1) First of all sort the string in ascending or descending order on the basis of ascii value of its character. 

Step 2)I don't know the ascii value of @ and % but whatever may be the ascii value the string will convert into a new string where similar character will be one after the other.
e.g. ascendingstr="6aaabddg@@%%" 

Step 3) Now one could simply iterate through the string checking whether are two aside character are same or not if yes then don't add it to set and if no then add it.

此外,此实现可以在ascii支持的超过26个英文字母字符上工作。

答案 3 :(得分:0)

for str in ... {
    bool repeated = 0;
    for (int i = 0; i < str.length(); ++i) {
        for (int j = i + 1; j < str.length(); ++j) {
            if(str.charAt(i) == str.charAt(j)) {
                repeated = 1;
                break;
            }
        }
        if (repeated) break;
    }

    if (repeated) // this str should not be added
    else napisy.add(str);
}

答案 4 :(得分:0)

为了做到这一点,首先检查要添加的字符串是否包含重复字符,如果它不是那么只将它添加到SET

下面是一个函数的编码,它告诉字符串是否包含双字符。如果返回true,则string不包含重复的字符。

boolean check(String str)
{
int frequ[]=new int[26];
for(int i=0;i<26;i++)
frequ[i]=0;
for(char ch='A';ch<'Z';ch++)
{
int fc=0;
for(int i=0;i<str.length();i++)
{
char c=str.charAt(i);
if(c==ch)
fc++;
}
frequ[(int)ch-65]=fc;
}

//not frequ array has frequency of all characters in string

for(int i=0;i<26;i++)
{
if(frequ[i]>1)//occuring more then 1
return false;
}
return true;
}

答案 5 :(得分:0)

您可以使用以下简化代码(使用流)检查唯一字符的输入,然后只添加到set对象。

Set<String> napisy = new HashSet<>();
String input = "ABC";

//Check if input is unique chars & then only add to Set
// if the length of chara stream is not same as input, then chars are repeated
if((input.chars().mapToObj(i->(char)i)).distinct().count() == input.length()) {
    napisy.add(input);
}

答案 6 :(得分:-1)

您可以检查字符串中是否有重复的字母

public static boolean isUniqueChars(String str) {
    if (str.length() > 256) {
        return false;
    }
    int checker = 0;
    for (int i = 0; i < str.length(); i++) {
        int val = str.charAt(i) - 'a';
        if ((checker & (1 << val)) > 0) return false;
        checker |= (1 << val);
    }
    return true;
}

然后将其添加到集合中,如果为true

类似

boolean isUnique = isUniqueChars ( yourString);
if (isUnique)
yourSet.add(yourString);

编辑:由于此行if (str.length() > 256),此实现仅适用于ASCII字符

答案 7 :(得分:-1)

使用add()方法在集合中添加字符串的字符。 add()方法只添加元素,如果它们不重复。如果它们重复,则返回false。

以下代码用于检查字符串是否包含重复的字符。

public static void main(String args[]) { 
  String s="ABBC";


  Set<Character> set = new HashSet<Character>();
  try {
     for(int i = 0; i < 4; i++) {
        if(!set.add(s.charAt(i))){
             System.out.println("repeated");
             return;
        }
     }
      System.out.println("non repeated");

  }
  catch(Exception e) {}

  } 

答案 8 :(得分:-1)

另一种解决方案:

String a = "ABCC";

    char[] dizi = a.toCharArray();
    List<Character> array = new ArrayList<>();
    for (Character c : dizi) {
        array.add(c);
    }
    Set<Character> set = new HashSet<>(array);