1.1. Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures?
我想到的是位图法。但是位图法有一个缺点,如果用int的话,也只能表示32的字符。看着答案是用的256的那个哈希,这难道不是额外的空间吗?不过后面答案给了第二个方案是用的位图法。给出C++代码
bool isUniqueChars(char * chr)
{
bool char_set[256] = {false}; while (*chr != '\0') { int value = *chr; if (char_set[value] == true) return false; else char_set[value] = true; } return true;}
bool isUniqueChars2(char * chr){ int checker = 0; while(*chr !=='\0') { int value = *chr - 'A'; if (checker & (1<<value) > 0) return false; else checker |= (1<<value); } return true;}
本文介绍了一种用于确定字符串中所有字符是否唯一的算法,并提供了两种实现方式:一种使用256大小的布尔数组来标记已出现的字符;另一种采用位图方法通过按位运算检查字符重复情况。
710

被折叠的 条评论
为什么被折叠?



