面试题 01.01.判定字符是否唯一
题目描述
实现一个算法,确定一个字符串 s 的所有字符是否全都不同。
示例1
输入: s = “leetcode”
输出: false
示例2
输入: s = “abc”
输出: true
限制
0 <= len(s) <= 100
如果你不使用额外的数据结构,会很加分。
示例代码
Java 哈希表
public class Question01 {
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.isUnique("leetcode"));
System.out.println(s.isUnique("abc"));
}
}
class Solution {
public boolean isUnique(String astr) {
char[] chars = astr.toCharArray();
int n = chars.length;
int[] frequency = new int[256];
for (int i = 0; i < n; i++) {
if(frequency[(int)chars[i]] == 0)
frequency[(int)chars[i]]++;
else
return false;
}
return true;
}
}
Java 提交结果
执行用时:0 ms, 在所有 Java 提交中击败了100.00% 的用户
内存消耗:36 MB, 在所有 Java 提交中击败了83.93% 的用户