實現一個算法,確定一個字符串 s 的所有字符是否全都不同。
示例 1:
輸入: s = "leetcode"
輸出: false
示例 2:
輸入: s = "abc"
輸出: true
限制:
0 <= len(s) <= 100
如果你不使用額外的數據結構,會很加分。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/is-unique-lcci
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
解題
/**
* 思路:
* 1、定義一個bool型大小爲256的數組array,然後遍歷輸入的字符串,每遍歷一個字符,令int型變量val等於該字符的的ASCII碼,
* 2、如果這個字符之前都沒有出現過,那麼令array[val]等於true,如果這個字符之前出現過了,也就是array[val]已經等於true了,就返回false。
* 3、當字符串中所有字符都遍歷結束後,如果沒有返回false,那麼說明字符串中沒有重複的字符,返回true。
*
* @param astr
* @return
*/
public static boolean isUnique(String astr) {
boolean[] charset = new boolean[256];
for (int i = 0; i < astr.length(); i++) {
int val = (int) astr.charAt(i);//取出字符,轉換爲ASCII碼
if (charset[val]) {
return false;
}
charset[val] = true;
}
return true;
}