【问题标题】:Java program to print a character which is available only one time in the string [duplicate]Java程序打印字符串中只能使用一次的字符[重复]
【发布时间】:2019-03-01 08:21:49
【问题描述】:

我试图从一个字符串中打印一个字符,该字符在字符串中只出现一次。这是我正在使用的代码,但它始终将答案显示为 H。

我该如何解决这个问题?

class StringRepeat {

    static int i,j;

    public static void main(String[] args) {
        String s1 = "How are How";
        outer:for(i=0;i<=s1.length(); i++)
        {
            inner:for(j=1;j<s1.length(); j++)
            {
              if (s1.charAt(i) != s1.charAt(j))
                break outer;
            }
        }
        System.out.println(s1.charAt(i));
    }
}

【问题讨论】:

  • 你有几个答案,有几个应该回答你的问题。请标记您选择的解决方案。

标签: java arrays string search


【解决方案1】:

基本上,您可以通过两种方式解决这个问题 - 蛮力(使用数组)和更智能(使用地图)。

蛮力方式

对于输入字符串中的每个字符,检查它是否与其他字符相同:

public void uniqueCharsBruteForce(String input) {
    for (int i = 0; i < input.length(); ++i) {
        char candidate = input.charAt(i);
        if (!contains(input, candidate, i)) {
            System.out.println(candidate);
        }
    }
}

private boolean contains(String input, char candidate, int skipIndex) {
    for (int i = 0; i < input.length(); ++i) {
        if (i == skipIndex) {
            continue;
        }
        if (candidate == input.charAt(i)) {
            return true;
        }
    }
    return false;
}

代码很简单但是很慢,所以只用于短字符串。时间复杂度为O(n^2)

使用地图

在遍历输入时,计算每个字符出现的次数。最后,只打印只出现一次的那些:

public void uniqueCharsBetter(String input) {
    Map<Character, Integer> occurences = new HashMap<>();
    for (int i = 0; i < input.length(); ++i) {
        Character key = Character.valueOf(input.charAt(i));
        occurences.put(key, occurences.getOrDefault(key, 0) + 1);
    }
    occurences.entrySet().forEach(entry -> {
        if (entry.getValue().intValue() == 1) {
            System.out.println(entry.getKey());
        }
    });
}

这可以进一步优化,但这可能足以满足您的要求。时间复杂度为O(n)

【讨论】:

    【解决方案2】:
    1. 如果没有唯一的,这将给出一个StringIndexOutOfBoundsException 找到字符:

      outer:for(i=0;i<=s1.length(); i++)
      

      替换为

      int i = 0;
      outer: for(;i<s1.length(); i++)
      
    2. 不需要内部标签,您需要开始搜索 从0,而不是1,所以替换

      inner:for(j=1;j<s1.length(); j++)
      

      for(int j=0;j<s1.length(); j++)
      
    3. 你的测试倒置了。如果ij 处的字符是 同样,您需要继续使用外循环。此外,您还需要 确保您在i==j 时不进行比较。所以你的测试从:

      if (s1.charAt(i) != s1.charAt(j))
        break outer;
      

      if (i!=j && s1.charAt(i) == s1.charAt(j))
        continue outer;
      
    4. 如果内部 for 循环终止,即到达 字符串,那么i处的字符是唯一的,所以我们需要突破 外循环。

    5. 退出外循环时,您需要确定是否找到了唯一元素,如果i &lt; s1.length() 就是这种情况。

    把这一切放在一起,我们得到:

    String s1= "How are How";
    int i = 0;
    outer: for(;i<s1.length(); i++)
    {
        for(int j=0;j<s1.length(); j++)
        {
          if (i!=j && s1.charAt(i) == s1.charAt(j))
           continue outer;
        }
        break;
    }
    if(i<s1.length()) System.out.println(s1.charAt(i));
    

    这里是代码的链接 (IDEOne)。

    【讨论】:

    • 它没有显示任何输出...没有编译时错误。程序在运行后执行后终止。
    • 真的,当我运行它时,它会打印出a。我在 IDEOne 上添加了一个代码链接,您可以在那里运行它。
    • 非常感谢....我的问题已经解决了。
    • 你能告诉我外部 for 循环是如何工作的吗?我从来没有见过这种for循环。
    • @SirRaffleBuffle 我认为问题不在于它不打印出a,而是它只打印出a,而不是仅打印出的其余字符出现一次。
    【解决方案3】:

    这将打印出在文本中只出现一次的每个字符。

    final String s1 = "How are How";
    outer:for(int i = 0; i < s1.length(); i++)
    {
        for(int j = 0; j < s1.length(); j++)
        {
            if(s1.charAt(i) == s1.charAt(j) && i != j)
            {
                continue outer;
            }
        }
        System.out.println(s1.charAt(i);
    }
    

    【讨论】:

      【解决方案4】:

      试试这个

      String s = inputString.toLowerCase();
      
      boolean[] characters = new boolean[26];
      for(int i = 0; i < 26; i++)
          characters[i] = true;
      
      for(int i = 0; i < s.length(); i++)
      {
          if(characters[s.charAt(i) - 'a'])
          {
              System.out.println(s.charAt(i));
              characters[s.charAt(i) - 'a'] = false;
          }
      }
      

      希望这会有所帮助。我假设您将小写和大写视为相同,否则您可以相应地进行修改

      【讨论】:

      • 这甚至不能解决问题。
      • 你能修改我的代码吗?
      • @TheJavaGuy-IvanMilosavljević 能否请您详细说明为什么它不起作用,并且考虑到时间复杂度,这是解决此类问题的最佳策略
      • @AviralAhuja 虽然您的代码确实有效,但它并不能解决给定的问题。如果一个字符重复多次,则根本不应该打印。无论字符串中字符出现的次数如何,您的代码都会打印一次字符。
      • @AviralAhuja 我将尝试用伪代码重新表述。 OP 需要一个执行此操作的代码:if (characterAppearsOnlyOnce) print character。但是您的代码会这样做print every character once
      猜你喜欢
      • 2020-01-24
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 2017-06-25
      • 1970-01-01
      • 2018-07-27
      • 1970-01-01
      • 2017-04-15
      相关资源
      最近更新 更多