Cracking the coding interview--Q1.1

本文介绍了一种使用ASCII和位操作来检查字符串中所有字符是否唯一的算法。提供了两种方法:一种利用ASCII码范围定义一个布尔数组追踪字符出现状态;另一种通过位操作在一个整型数组中表示字符状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://www.hawstein.com/posts/1.1.html--原文C++实现


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


Java实现:
public class TestDemo01 {
public static void main(String[] args) {
String str = "123rtxhs4567890-=_+<>?LHFCDZWARIJ:Jadclm;./'[";
boolean resultASCII = isUniqueByASCII(str);
System.out.println("resultASCII=" + resultASCII);
boolean resultBit = isUniqueByBit(str);
System.out.println("resultBit=" + resultBit);
}
    /**
     * 扩展的ASCII只有256个字符,定义一个数组,
     * 保存每个字符的状态,可根据每个字符的状态判断是否重复
     * @param str
     * @return
     */
public static boolean isUniqueByASCII(String str) {
boolean[] tempArray = new boolean[256];
for (int i = 0; i < str.length(); i++) {
int charNum = str.charAt(i);
if (tempArray[charNum] != false) {
return false;
}
tempArray[charNum] = true;
}
return true;
}
    /**
     * 扩展的ASCII只有256个字符,定义一个8位整形数组,
     * 每个整型数可表示32个字符的状态,根据每个字符的状态判断
     * @param str
     * @return
     */
public static boolean isUniqueByBit(String str) {
int[] tempArr = new int[8];
for (int i = 0; i < str.length(); i++) {
int charNum = str.charAt(i);
int tempArrIndex = charNum / 32;
int tempArrRes = charNum % 32;
if ((tempArr[tempArrIndex] & (1 << tempArrRes)) != 0) {
return false;
}
tempArr[tempArrIndex] |= (1 << tempArrRes);
}
return true;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值