Top 150 Questions - 1.1

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

这个题主要操作集中在查找上面,所以首先想到的就是哈希,时间复杂度为O(n);字符不超过256,定义256大小的数组就ok了。书上指出的其他方法还有O(n^2)的蛮力查找;O(nlogn)排序然后检查是否有相同。

package Question1_1;

import java.util.HashSet;
import java.util.Set;

public class Question1_1
{
	public static void main(String[] args)
	{
		Question1_1 q = new Question1_1();
		String[] testStrings = {"abcdefg", "abcdefe", "1234e;z.", "32,./??'"};
		
		for (String x : testStrings)
			System.out.print(q.CheckUniqueChar1(x) + " ");
		System.out.println();
		for (String x : testStrings)
			System.out.print(q.CheckUniqueChar2(x) + " ");
	}
	
	/*
	 * 	Using hash table data structure
	 */
	public boolean CheckUniqueChar1(String s)
	{
		Set<Character> set = new HashSet<Character>();
		int i;
		
		for (i = 0; i < s.length(); i++)
			if (!set.contains(s.charAt(i))) set.add(s.charAt(i));
			else return false;
		
		return true;
	}
	
	/*
	 * 	Without using hash table, but essentially the same implementation
	 */
	public boolean CheckUniqueChar2(String s)
	{
		// char variable (ASCII) cannot exceed 256
		boolean[] chars = new boolean[256];
		int i;
		
		// if chars[s.charAt(i)] == false, then it hasn't occurred ever
		for (i = 0; i < s.length(); i++) 	
			if (chars[s.charAt(i)] == false) chars[s.charAt(i)]= true; 
			else return false;
		
		return true;
	}
}


 

PS:快速排序方法:

	/*
	 *  Using quick sort
	 */
	public boolean CheckUniqueChar3(String a)
	{
		char[] s = a.toCharArray();
		return CheckUniqueChar3Helper(s, 0, s.length - 1);
	}
	
	private boolean CheckUniqueChar3Helper(char[] s, int left, int right)
	{
		// choose the left element as pivot for simplicity
		if (left > right)
			return true;
		
		int p = s[left];
		
		// partition around p
		int i, j;
		for (i = left + 1, j = left + 1; j <= right; j++)
		{
			if (p > s[j])
			{
				char temp = s[i];
				s[i++] = s[j];
				s[j] = temp;
			}
			else if (p == s[j])
			{
				return false;
			}
		}
		
		char temp = s[i-1];
		s[i-1] = s[left];
		s[left] = temp;
		
		// recursive call
		if (CheckUniqueChar3Helper(s, left, i-2) == false)
			return false;
		if (CheckUniqueChar3Helper(s, i, right) == false)
			return false;
		
		return true;
	}
}


 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值