资讯专栏INFORMATION COLUMN

[LintCode] Unique Characters

DevWiki / 2689人阅读

摘要:用做,十分简单。如果不使用之外的数据结构的话,可以用来做。不过只能过纯字母字符的。

Problem

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?

Note

用HashSet做,十分简单。
如果不使用String之外的数据结构的话,可以用bit manipulation来做。不过只能过纯字母字符的testcase。

Solution
public class Solution {
    public boolean isUnique(String str) {
        HashSet set = new HashSet();
        for (int i = 0; i < str.length(); i++) {
            if (!set.contains(str.charAt(i))) {
                set.add(str.charAt(i));
            }
            else return false;
        }
        return true;
    }
}
public class Solution {
    public boolean isUnique(String s) {
        int checker = 0;
        for (int i = 0; i < s.length(); i++) {
            int cur = s.charAt(i) - "a";
            if ((checker & (1 << cur)) > 0) {
                return false;
            }
            checker |= 1 << cur;
        }
        return true;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65694.html

相关文章

  • [LintCode/LeetCode] Minimum Window Substring

    Problem Given a string source and a string target, find the minimum window in source which will contain all the characters in target. Notice If there is no such window in source that covers all charac...

    Corwien 评论0 收藏0
  • [LintCode] String Homomorphism

    Problem Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with an...

    tanglijun 评论0 收藏0
  • [LintCode] Compare Strings

    摘要:建立一个长度为的数组,每一位对应那个字母出现的个数,先遍历,对数组做增操作,再遍历,对数组做减操作。 Problem Compare two strings A and B, determine whether A contains all of the characters in B. The characters in string A and B are all Upper Ca...

    avwu 评论0 收藏0
  • [LintCode/LeetCode] Unique Paths II

    摘要:和完全一样的做法,只要在初始化首行和首列遇到时置零且即可。对了,数组其它元素遇到也要置零喏,不过就不要啦。 Problem Follow up for Unique Paths: Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle...

    firim 评论0 收藏0
  • [LintCode/LeetCode] First Unique Character in a S

    Problem Given a string, find the first non-repeating character in it and return its index. If it doesnt exist, return -1. Example Given s = lintcode, return 0. Given s = lovelintcode, return 2. Tags A...

    Xufc 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<