1.1 判断字符串是否由唯一字符组成

本文介绍了一个简单的算法,用于检查一个字符串中的所有字符是否都是唯一的,即没有任何字符重复出现。该算法通过一个布尔型数组实现,避免了使用额外的数据结构。

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

原文:

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

译文:

实现一个算法来判断一个字符串中的字符是否唯一(即没有重复).不能使用额外的数据结构。(即只使用基本的数据结构)


解答:

空间换时间

哈希表解决:

package com.zhuyu_deng.test;

public class Test
{
	static boolean isUniqueChar(String x)
	{
		boolean check[] = new boolean[256];  // 初始化为false;
		for(int i = 0, len = x.length(); i < len; ++i)
		{
			int index = (int)x.charAt(i);
			if (check[index] == true)
				return false;
			check[index] = true;
		}
		return true;
	}
	
	public static void main(String args[])
	{
		String s = "abcdefghijklmnopqrstuvwxyzABCD1234567890";
		boolean ans = isUniqueChar(s);
		System.out.println(ans);
	}
}

ps:类似的题目还有下面这个。

在一个字符串中找到第一个只出现一次的字符


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值