is String having Unique Character Using HashMap, Time: O(n), Space: O(1) - Java Algorithm

Java examples for Algorithm:String

Description

is String having Unique Character Using HashMap, Time: O(n), Space: O(1)

Demo Code

import java.util.HashMap;
import java.util.Map;

public class Main {
  public static boolean isUnique(String str){
    // Time: O(n), Space: O(1)
    Map<Character, Boolean> table=new HashMap<Character, Boolean>();
    if(str.length()==0 || str.length()==1) return true;
    else if(str.length()>=256) return false;
    for(int i=0; i<str.length(); i++){
      if(table.containsKey(str.charAt(i))) return false;
      else{/*from  w ww  .j  a v  a  2s . co m*/
        table.put(str.charAt(i), true);
      }
    }
    return true;
  }
  // Test
  public static void main(String[] args){
    String str="Hello";
    System.out.print(isUnique(str)+" ");
    String str_2="";
    System.out.print(isUnique(str_2)+" ");
    String str_3="He";
    System.out.print(isUnique(str_3)+" ");
    String str_4="  ";
    System.out.print(isUnique(str_4)+" ");
  }
}

Related Tutorials