簡體   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