Two ways to Check Unique Char using Java

/**
 * 
 */
package com.thys.michels;

import java.util.HashSet;

/**
 * @author tmichels
 *
 */
public class Question1_1 {

	/**
	 * Use a hash map to count the amount of same values and see if all are 1. Using an HashMap
	 */
	
	
	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) + " " + isUniqueChars2(word));
        }
	}
	//public static char[] getchararray;
	private static boolean isUniqueChars2(String word) {
		//unicode value of an char int charat
		for (int k = 1; k < word.length() -1 ; k++)
		{
			for (int m = 0; m < k; m++)
			{
				if ((int) word.charAt(m) == (int) word.charAt(k))
				{
					return false;
				}
			}		
		}
		
		return true;
	}

	private static boolean isUniqueChars(String word) {
		// TODO Auto-generated method stub
		HashSet wordset = new HashSet();
		for (int k = 0; k < word.length(); k++)
		{
			wordset.add(word.charAt(k));
		}
		if (wordset.size() == word.length())
		{
			return true;
		}
		else
			return false;
	}

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: