In this article, we will discuss how to check if a string has all unique characters.
This is a frequently asked interview question. Here are few solutions in Java for this :
Solution 1 : Check if string has all unique characters using String library functions
package com.topjavatutorial; public class UniqueCharactersDemo { public static void main(String[] args) { System.out.println(hasUniqueCharacters("hello")); } private static boolean hasUniqueCharacters(String str){ for(char ch : str.toCharArray()){ if(str.indexOf(ch) == str.lastIndexOf(ch)) continue; else return false; } return true; } }
Output :
false
Solution 2 : Check if string has unique characters using HashMap
private static boolean checkUniqueUsingMap(String str){ HashMap<Character,Integer> charMap = new HashMap<Character,Integer>(); for(char ch : str.toCharArray()){ if(charMap.containsKey(ch)){ return false; } else charMap.put(ch, 1); } return true; }
Solution 3 : Compare each character to every other character without using an additional data structure
public static boolean IsUniqueChars(String s) { for (int i = 0; i < s.length() - 1; i++) { for (int k = i + 1; k < s.length(); k++) { if (s.charAt(i) == s.charAt(k)) return false; } } return true; }
This approach take O(n^2) time.
Solution 4 : Check if string has all unique characters without using an additional data structure in O(n) time
//Source: Cracking the Coding Interview Book public static boolean isUniqueChars(String str) { boolean[] char_set = new boolean[256]; for (int i = 0; i < str.length(); i++) { // Get the ascii value of the character in str at position `i`. int val = str.charAt(i); // If char_set[val] has been set, that means that this character was // already present in the string. if (char_set[val]) return false; // If the character hasn't been encountered yet, mark it as present // in the string char_set[val] = true; } // The string has unique chars if we reach this point return true; }
© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post