返回介绍

lcci / 01.01.Is Unique / README_EN

发布于 2024-06-17 01:04:43 字数 3057 浏览 0 评论 0 收藏 0

01.01. Is Unique

中文文档

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

Solution 1: Bit Manipulation

Based on the examples, we can assume that the string only contains lowercase letters (which is confirmed by actual verification).

Therefore, we can use each bit of a $32$-bit integer mask to represent whether each character in the string has appeared.

The time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$.

class Solution:
  def isUnique(self, astr: str) -> bool:
    mask = 0
    for c in astr:
      i = ord(c) - ord('a')
      if (mask >> i) & 1:
        return False
      mask |= 1 << i
    return True
class Solution {
  public boolean isUnique(String astr) {
    int mask = 0;
    for (char c : astr.toCharArray()) {
      int i = c - 'a';
      if (((mask >> i) & 1) == 1) {
        return false;
      }
      mask |= 1 << i;
    }
    return true;
  }
}
class Solution {
public:
  bool isUnique(string astr) {
    int mask = 0;
    for (char c : astr) {
      int i = c - 'a';
      if (mask >> i & 1) {
        return false;
      }
      mask |= 1 << i;
    }
    return true;
  }
};
func isUnique(astr string) bool {
  mask := 0
  for _, c := range astr {
    i := c - 'a'
    if mask>>i&1 == 1 {
      return false
    }
    mask |= 1 << i
  }
  return true
}
function isUnique(astr: string): boolean {
  let mask = 0;
  for (let j = 0; j < astr.length; ++j) {
    const i = astr.charCodeAt(j) - 'a'.charCodeAt(0);
    if ((mask >> i) & 1) {
      return false;
    }
    mask |= 1 << i;
  }
  return true;
}
/**
 * @param {string} astr
 * @return {boolean}
 */
var isUnique = function (astr) {
  let mask = 0;
  for (const c of astr) {
    const i = c.charCodeAt() - 'a'.charCodeAt();
    if ((mask >> i) & 1) {
      return false;
    }
    mask |= 1 << i;
  }
  return true;
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文