CareerTop Question 1

本文详细介绍了在不使用额外数据结构的情况下,如何通过原生方法判断一个字符串是否包含所有唯一的字符,并提供了两种解决方案:利用ASCII码进行判断和位运算实现。这些方法适用于对内存和资源效率有严格要求的场景。

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

Data Structures - Arrays and Strings:

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

My Original Solution:

        private static boolean uniqueStrByHushTable(String str) {
		boolean flag = false;
		char[] chars = str.toCharArray();
		HashSet<Character> hashSet = new HashSet<Character>();
		for(int i = 0; i < chars.length; i ++) {
			hashSet.add(chars[i]);
		}
		if(hashSet.size()==chars.length) {
			flag = true;
		}
		return flag;
	}

 

Book original solution:

 

	private static boolean uniqueStrByASCII(String str) {
		boolean[] char_val = new boolean[256];
		for (int i = 0; i < str.length(); i++) {
			int val = str.charAt(i);
			if (char_val[val]) {
				return false;
			}
			char_val[val] = true;
		}
		return true;
	}

 

Book original solution 2:

 

private static boolean isUniqueStr(String str) {
		int checker = 0;
		for (int i = 0; i < str.length(); i++) {
			int val = str.charAt(i) - 'a';
			if ((checker & (i << val)) > 0) {
				return false;
			}
			checker |= (1 << val);
		}
		return true;
	}

 

Have no idea about how to check unique string without any data structure.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值