Skip to content

Latest commit

 

History

History
135 lines (106 loc) · 2.59 KB

README.md

File metadata and controls

135 lines (106 loc) · 2.59 KB

English Version

题目描述

实现一个算法,确定一个字符串 s 的所有字符是否全都不同。

示例 1:

输入: s = "leetcode"
输出: false 

示例 2:

输入: s = "abc"
输出: true

限制:

  • 0 <= len(s) <= 100
  • 如果你不使用额外的数据结构,会很加分。

解法

根据示例,可以假定字符串中只包含小写字母(实际验证,也符合假设)。

用 bitmap 标记小写字母是否出现过。

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;
    }
};

...