【笔试】57、确定一个字符串的所有字符是否都不同

</pre><pre name="code" class="java">/****************************************************************************************
 *题目:实现一个算法,确定一个字符串的所有字符是否都不同。假设不允许使用其他的数据结构
 *时间:2015年10月12日20:06:13
 *文件:DiffChar.java
 *作者:cutter_point
 ****************************************************************************************/
package bishi.Offer50.y2015.m10.d12;

public class DiffChar
{
	public boolean diff(String s)
	{
		if(s == null || s == "")
			return true;
		//我们通过这个数组进行判断是否存在
		boolean sc[] = new boolean[256];
		for(int i = 0; i < s.length(); ++i)
		{
			char c = s.charAt(i);
			if(sc[c] == true)
			{
				//如果已经存在了
				return false;
			}//if
			sc[c] = true;
		}//for
		
		return true;
	}
	
	/**
	 * 假设我们的字符只有a-z,那么我们也可以通过位运算实现
	 * @param str
	 * @return
	 * @throws Exception 
	 */
	public boolean isUniqueChars(String str) throws Exception
	{
		if(str.length() > 26 || str == null)
		{
			//如果字符数量超过a-z的总数,那么就一定有重复
			return false;
		}//if
		
		int checkchar = 0;	//首先是26个0,也即是一个都没有出现过
		//遍历所有的字符
		for(int i = 0; i < str.length(); ++i)
		{
			if(str.charAt(i) < 'a' || str.charAt(i) > 'z')
			{
				throw new Exception("字符串不和要求");
			}//if
			//取得这个字符的位置数
			int num = str.charAt(i) - 'a';
			//我们判断checkchar中是否含有这个字符的位置
			if((checkchar & (1 << num)) == 1)
			{
				//判断,如果是1&1的话,结果就是1,就是存在重复
				return false;
			}//if
			
			//把这个位置设置为1
			checkchar = checkchar | (1 << num);
		}//for
		
		return true;
	}

	public static void main(String[] args) throws Exception
	{
		Character c = 'c';
		String s[] = {"", null, "1213", "abc", "aaaaa", "jksg", "asdasdqc"};
		DiffChar d = new DiffChar();
		for(int i = 0; i < s.length; ++i)
			System.out.println(d.diff(s[i]));
		String s2[] = {"avsdf","aaaa","ashdahihsa","123"};
		System.out.println("======================");
		for(int i = 0; i < s2.length; ++i)
			System.out.println(d.isUniqueChars(s2[i]));
	}

}


输出:

true
true
Exception in thread "main" false
true
false
true
false
======================
true
false
false
java.lang.Exception: 字符串不和要求
at bishi.Offer50.y2015.m10.d12.DiffChar.isUniqueChars(DiffChar.java:51)
at bishi.Offer50.y2015.m10.d12.DiffChar.main(DiffChar.java:79)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值