Java program to check string has all unique character

This question is very popular in the first round of technical interview for the freshers and also it's kind of homework activity. The coding practice is necessary to be logical on the logical questions like how to balanced parentheses and find the second largest element from an array. My suggestion for freshers to do always practice on such question like calculating Fibonacci series, finding factorial of given number and all.

In this post, going to show you some simple approach to check if string contains duplicate characters.

package com.javamakeuse.poc;

import java.util.HashSet;
/**
 * 
 * @author javamakeuse
 *
 */
public class UniqueChars {

 public static boolean isUnique(String str) {
  String lowerCase = str.toLowerCase();
  HashSet<Character> charSet = new HashSet<Character>(lowerCase.length());
  for (int i = 0; i < lowerCase.length(); i++) {
   if (!charSet.add(lowerCase.charAt(i))) {
    return false;
   }
  }
  return true;
 }

 public static void main(String[] args) {
  System.out.println(isUnique("javamakeuse"));
 }
}

OUTPUT:
false

Comments

Popular posts from this blog

JSP Servlet Interview Questions For Freshers Series 1

What are the core classes and interfaces of hibernate 4

Java Banking Finance Services and Insurance (BFSI) domain interview questions