Skip to content

Latest commit

 

History

History
132 lines (101 loc) · 2.2 KB

README_EN.md

File metadata and controls

132 lines (101 loc) · 2.2 KB

中文文档

Description

Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?

Example 1:

Input:  = "leetcode"

Output: false

Example 2:

Input: s = "abc"

Output: true

Note:

  • 0 <= len(s) <= 100

Solutions

Python3

class Solution:
    def isUnique(self, astr: str) -> bool:
        bitmap = 0
        for c in astr:
            pos = ord(c) - ord('a')
            if (bitmap & (1 << pos)) != 0:
                return False
            bitmap |= (1 << pos)
        return True

Java

class Solution {
    public boolean isUnique(String astr) {
        int bitmap = 0;
        for (char c : astr.toCharArray()) {
            int pos = c - 'a';
            if ((bitmap & (1 << pos)) != 0) {
                return false;
            }
            bitmap |= (1 << pos);
        }
        return true;
    }
}

JavaScript

/**
 * @param {string} astr
 * @return {boolean}
 */
var isUnique = function (astr) {
    let bitmap = 0;
    for (let i = 0; i < astr.length; ++i) {
        const pos = astr[i].charCodeAt() - 'a'.charCodeAt();
        if ((bitmap & (1 << pos)) != 0) {
            return false;
        }
        bitmap |= 1 << pos;
    }
    return true;
};

Go

func isUnique(astr string) bool {
	bitmap := 0
	for _, r := range astr {
		pos := r - 'a'
		if (bitmap & (1 << pos)) != 0 {
			return false
		}
		bitmap |= (1 << pos)
	}
	return true
}

C++

class Solution {
public:
    bool isUnique(string astr) {
        int bitmap = 0;
        for (char c : astr) {
            int pos = c - 'a';
            if ((bitmap & (1 << pos)) != 0) {
                return false;
            }
            bitmap |= (1 << pos);
        }
        return true;
    }
};

...