简体   繁体   English

查找字符串中所有不重复的字符

[英]find all non repeated character in a string

can you help me to to this java program? 你可以帮我这个Java程序吗? i have a two string i need to determine what are the characters that has no repeated letters. 我有两个字符串,我需要确定没有重复字母的字符。 the inputs are: love, life the out put will be: ovif 输入是:爱,生活的投入将是:ovif

it will removed all the character that has a duplicate. 它将删除所有重复的字符。

here's the code that i have but it only print and find the letters that has duplicate. 这是我拥有的代码,但它只能打印并找到重复的字母。

public static void main(String[] args) {
    Map<Character, Integer> map = new HashMap<Character, Integer>(); 

    input = new Scanner(System.in);
    String aw, bw;

    System.out.println("Input First Word: ");
    aw=input.next();
    System.out.println("Input Second Word: ");
    bw=input.next();
    String s = aw+bw;
    char[] chars = s.toCharArray();

    for(Character ch:chars){
      if(map.containsKey(ch)){
         map.put(ch, map.get(ch)+1);
      } else {
         map.put(ch, 1);
      }
    }

    Set<Character> keys = map.keySet();


    for(Character ch:keys){
      if(map.get(ch) > 1){
        System.out.println(ch+" ");
      }
    }
}

i want to print the characters that it removed in that program. 我想打印在该程序中删除的字符。

for(Character ch:keys){
  if(map.get(ch) == 1){
    System.out.println(ch+" ");
  }
}

Will print out all the characters that appear once. 将打印出所有出现一次的字符。 You add every character in both strings to the map, so characters which only appear once will have value 1. 您将两个字符串中的每个字符都添加到地图,因此仅出现一次的字符将具有值1。

A Set is excellent for checking history. Set非常适合检查历史记录。

public void test() {
    String s = "love life";
    Set<Character> unique = new HashSet<>();
    Set<Character> duplicate = new HashSet<>();
    for (char c : s.toCharArray()) {
        // Have we seen this one before already.
        if (!duplicate.contains(c)) {
            if (!unique.add(c)) {
                // It was already there.
                unique.remove(c);
                // Mark it as duplicate.
                duplicate.add(c);
            }

        }
    }
    System.out.println("Unique:" + Arrays.toString(unique.toArray(new Character[0])));
}

Manipulating Set s is simple: 操作Set很简单:

Set<Character> inString(String s) {
    Set<Character> in = new HashSet<>();
    for (char c : s.toCharArray()) {
        in.add(c);
    }
    return in;
}

public void test() {
    Set<Character> inFirst = inString("glass");
    Set<Character> inSecond = inString("bass");
    Set<Character> inFirstButNotInSecond = new HashSet<>(inFirst);
    inFirstButNotInSecond.removeAll(inSecond);
    System.out.println("In first but not in second:" + inFirstButNotInSecond);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM