LintCode Unique Characters 判断字符串是否没有重复字符

来源:互联网 发布:做淘宝如何提高销量 编辑:程序博客网 时间:2024/06/07 05:14

实现一个算法确定字符串中的字符是否均唯一出现

样例
给出”abc”,返回 true
给出”aab”,返回 false

挑战
如果不使用额外的存储空间,你的算法该如何改变?

Implement an algorithm to determine if a string has all unique characters.

Example
Given “abc”, return true.
Given “aab”, return false.

Challenge
What if you can not use additional data structures?

未用额外空间,时间复杂度O(n^2)

public class Solution {    /**     * @param str: a string     * @return: a boolean     */    public boolean isUnique(String str) {        for(int i = 0; i < str.length(); i++) {            for(int j = i + 1; j < str.length(); j++) {                if(str.charAt(i) == str.charAt(j))                    return false;            }        }        return true;    }}

使用额外空间,时间复杂度O(n)

public class Solution {    /**     * @param str: a string     * @return: a boolean     */    public boolean isUnique(String str) {        Set<Character> set = new HashSet<Character>();        for(int i = 0; i < str.length(); i++) {            if(set.contains(str.charAt(i)))                return false;            set.add(str.charAt(i));        }        return true;    }}
0 0
原创粉丝点击