Java program to check if a string has unique characters without using additional space

This post is about a java program to check whether a string has unique characters without using additional memory space. The program is implemented with the help of bit vector.

The program is as follows:

package com.programs;

/*
 * Program to check if the string contains duplicate characters in an efficient way.
 */

public class strdups {

 public static void main(String args[])

 {

  String textWithDuplicateCharacters = "aabbcdefghij";
  String textWithUniqueCharacters = "abcdefghijklmnopqrstuvwxyz";

  printOutput(isUnique(textWithDuplicateCharacters));
  printOutput(isUniqueEfficient(textWithDuplicateCharacters));

  System.out.println();

  printOutput(isUnique(textWithUniqueCharacters));
  printOutput(isUniqueEfficient(textWithUniqueCharacters));

 }

 public static boolean isUnique(String str)

 {

  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;

 }

 // Efficient program without additional memory space

 public static boolean isUniqueEfficient(String str)

 {

  int check = 0;

  for (int i = 0; i < str.length(); i++)

  {

   int val = str.charAt(i) - 'a';

   if ((check & (1 << val)) > 0)

   {

    return false;

   }

   check |= (1 << val);

  }

  return true;

 }

 public static void printOutput(boolean bool) {
  if (bool == false)

  {

   System.out.println(" There are duplicate characters in the string");

  }

  else

  {

   System.out.println(" The string contains only unique characters");

  }

 }

}

The output for this program is as follows:


 There are duplicate characters in the string
 There are duplicate characters in the string

 The string contains only unique characters
 The string contains only unique characters

Similar programs like this:

1) Java program to find the third largest element in an array.
2) Java program to check if a string is pangram
3) Linked list implementation in java

Please comment below if you have any questions.

Comments

Popular posts from this blog

Difference between "diff" and "sdiff" commands in Unix

Anonymous classes in C++