Java examples for Algorithm:String
is String having Unique Character Using Sort, Time: O(nlog(n)), Space: O(1)
import java.util.Arrays; public class Main { public static boolean isUnique(String str){ // Time: O(nlog(n)), Space: O(1) if(str.length()<=1) return true; else if(str.length()>256) return false; char[] characters=str.toCharArray(); Arrays.sort(characters);/*w w w .j a v a 2 s . com*/ for(int i=0; i<str.length()-1; i++){ if(characters[i]==characters[i+1]) return false; } 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)+" "); } }