請實現一個演算法,確定一個字串的所有字元是否全都不同。這裡我們要求不允許使用額外的儲存結構

來源:互聯網
上載者:User

**請實現一個演算法,確定一個字串的所有字元是否全都不同。這裡我們要求不允許使用額外的儲存結構。
給定一個string iniString,請返回一個bool值,True代表所有字元全都不同,False代表存在相同的字元。保證字串中的字元為ASCII字元。字串的長度小於等於3000。
測試範例:
“aeiou”
返回:True
“BarackObama”
返回:False**

package Question1_1;public class Question {    public static boolean isUniqueChars(String str) {        if (str.length() > 128) {            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;    }    public static boolean isUniqueChars2(String str) {        if (str.length() > 128) {            return false;        }        boolean[] char_set = new boolean[128];        for (int i = 0; i < str.length(); i++) {            int val = str.charAt(i);            if (char_set[val]) return false;            char_set[val] = true;        }        return true;    }    public static void main(String[] args) {        String[] words = {"abcde", "hello", "apple", "kite", "padle"};        for (String word : words) {            System.out.println(word + ": " + isUniqueChars(word) + " " + isUniqueChars2(word));        }    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.