编程算法 - 字符串相同 代码(Java)

字符串相同 代码(Java)


本文地址: http://blog.csdn.net/caroline_wendy


题目: 实现一个算法, 确定一个字符串的所有字符是否全都不同. 假使不允许使用额外的数据结构, 又该如何处理.


解法1:

使用数据结构, 设置boolean数组, 把值(value)作为数组的索引(index), 判断数组是否重复.


解法2:

不使用数据结构, 可以通过位(bit)进行判断, 把每个字母映射2进制数的一位, 或运算("|")更新数字的位, 与运算("&")判断是否相同.


代码:

/**
 * @time 2014年7月25日
 */
package array_string;

/**
 * @author C.L.Wang
 *
 */
public class StringCommon {

	public static boolean isUniqueChars(String str) {
		if (str.length() > 256) return false;
		boolean[] char_set = new boolean[256];
		for (int i=0; i<str.length(); i++) {
			int val = str.charAt(i);
			if(char_set[val]) {
				return false;
			}
			char_set[val] = true;
		}
		return true;
	}
	
	public static boolean isUniqueChar2(String str) {
		if (str.length() > 256) return false;
		int checker = 0;
		for (int i=0; i<str.length(); ++i) {
			int val = str.charAt(i);
			if ((checker&(1<<val)) > 0) return false;
			checker |= (1<<val);
		}
		return true;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String[] words = {"abcde", "hello", "apple", "kite", "padle"};
		for (String word : words) {
			System.out.println(word + ": " + isUniqueChars(word) + " " + isUniqueChar2(word));
		}
		
	}

}


输出:

abcde: true true
hello: false false
apple: false false
kite: true true
padle: true true






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ElminsterAumar

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值