繁体   English   中英

确定字符串是否具有所有唯一字符的算法

[英]Algorithm to determine if a string has all unique characters

我已经编写了此算法来确定字符串是否具有所有唯一字符,但是它给了我一些错误。 谁能帮助我改善代码。

它给了我一个错误,我正在复制uniquechar1方法,但是将其传递给if语句。

package nospacesinstrings;
import java.util.Scanner;

public class uniquechar {

    public static boolean uniquechar1(String s) {

        if (s == null || s.length() > 0 ) {
            return false;
        }

        for (int i = 0 ;i < s.length();i++) {
            for (int j = s.length() ;j > 0;j--) {
                if (i == j)
                   return false;
                else 
                   return true;
            }
        }
    }

    public static void main(String[] args) {

        String s ;
        System.out.println("Enter the string ");
        Scanner in = new Scanner(System.in);
        s = in.nextLine(); 
        if (uniquechar1(s) == true) {
            System.out.println("String has all the unique characters ");
        } else {
            System.out.println("String does not have all the unique characters ");
        }
    }
}

您顶部的支票向后看。 我认为您打算将s.length() < 1而不是s.length() > 0

您还需要在完成对字符串的迭代之前返回一个值。 仅当您遍历完整字符串而不返回false才应返回true

同样,您的双循环将总是最终将每个字符与其自身进行比较,因此该方法将返回false。 要在每个循环中使用a来执行此操作,您需要先停止操作,然后才能进入当前检查的索引。

for (int i = 0 ;i < s.length();i++){
    for (int j = s.length() ;j > i;j--){
        if (i == j )
        {return false ;}
    }
return true;

您也可以在走行时通过收集字符来避免遍历字符串两次。 像这样:

Stack<char> stack = new Stack<char>();
for (int i = 0 ;i < s.length();i++){
        if (stack.Contains(s[i]))
        {return false ;}
        stack.Push(s[i]);
    }
return true ;

最后,是否应该研究字符比较。 您是否希望即使两个字符都不相同(即使A == a或A!= a)也是失败的?

此算法应该可以工作。 我假设字符串中没有数字。 (已编辑以更正代码)。

public static boolean uniquechar1(String s) 
{
    if (s == null || s.length() == 0 )
        return true;
    // make sure no letter in alphabet occurs twice in the string.
    boolean[] letters = new boolean[26];
    s = s.toUpperCase();
    s = s.replaceAll(" ", "");
    for (int i = 0; i < s.length(); i++)
    {
        char ch = s.charAt(i);
        ch = (char) (ch - 'A');

        if (letters[ch] == true)
            return false;
        else
            letters[ch] = true;
    }

    return true;
}

这是一种测试器方法。

public static void main(String[] args)
{
    System.out.println( uniquechar1("Hello World!") );
    System.out.println( uniquechar1("A A") );   
    System.out.println( uniquechar1("ABC") );   
}  

输出:

false  
false  
true  

暂无
暂无

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

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