判断字符串是否没有重复字符
题目
实现一个算法确定字符串中的字符是否均唯一出现
样例
给出”abc”,返回 true
给出”aab”,返回 false
挑战
如果不使用额外的存储空间,你的算法该如何改变?
题解
1.不使用额外的存储空间的解法,时间复杂度为O(n^2)。
public class Solution {
/**
* @param str: a string
* @return: a boolean
*/
public boolean isUnique(String str) {
int n = str.length();
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n - 1; j++)
{
if ((int)str.charAt(i) == (int)str.charAt(j))
{
return false;
}
}
}
return true;
}
}
2.使用额外空间的解法,时间复杂度为O(n)。
可以用HashMap或者数组来记录字符是否已经出现过,由于本题无须获取重复字符的个数,仅需知道是否有字符重复。也就是用一个bit就可以判断一个字符是否重复。这样对于ASCII字符来说,用一个长度为4的int数组就可实现。
public class Solution {
/**
* @param str: a string
* @return: a boolean
*/
public boolean isUnique(String str) {
int[] arr = new int[4];
for (int i = 0; i < str.length(); i++)
{
int index = str.charAt(i) / 32;
int offset = (str.charAt(i) % 32 == 0 ? 32 : (str.charAt(i) % 32)) - 1;
if (((arr[index] >> offset) & 1) == 1)
{
return false;
}
else
{
arr[index] = arr[index] | (1 << offset);
}
}
return true;
}
}
Last Update 2016.9.7