实现一个算法确定字符串中的字符是否均唯一出现
样例
给出"abc"
,返回 true
给出"aab"
,返回 false
挑战
如果不使用额外的存储空间,你的算法该如何改变?
解题思路1:
利用hashSet去重,比较即可。
时间复杂度O(n),空间复杂度O(n)
public class Solution {
/*
* @param str: A string
* @return: a boolean
*/
public boolean isUnique(String str) {
// write your code here
Set<Character> set = new HashSet<>();
for(int i=0; i<str.length(); i++)
set.add(str.charAt(i));
if(str.length() != set.size())
return false;
else
return true;
}
}
解题思路2:
利用排序,依次比较
时间复杂度O(nlogn),空间复杂度O(1)
public class Solution {
/*
* @param str: A string
* @return: a boolean
*/
public boolean isUnique(String str) {
// write your code here
char[] ctr = str.toCharArray();
Arrays.sort(ctr);
for(int i=1; i<ctr.length; i++)
if(ctr[i] == ctr[i-1])
return false;
return true;
}
}