Top 150 1.1 unique character

1.1  Implement an algorithm to determine if a string has all unique characters .

What if you can not use additional data structures?

1. ASCII string or Unicode string

Unicode used 8,16 or 32 bits to store information whereas ASCII used 7 bits. (or now ASCII becomes 8 bits)

Unicode can represent more than 65000 characters/symbols as compared to ASCII only support 128 characters. 

Unicode characters are standardized to represent most of commonly used languages worldwide including asian/indian languages. But ASCII only used for frequent American English encoding. For example ASCII does not use symbol of pound or umlaut.

This is helping in common standard for document genration in any language independent of any custom software using custom mapping of characters. 

2. java bit operation

~ invert a bit pattern, can applied to any of the integral types, making every "0" a "1" and every "1" a "0".

<< shift a bit pattern to the left

>> shift a bit pattern to the right

>>> unsigned right shift operator, shift a zero into the leftmost position

& AND operation

^ exclusive OR operation sets the bit to 1 where the corresponding bits in its operands are different, and to 0 if they are the same

can be used to swap two integers without using intermediate.

a ^ = b;

b ^= a;

a ^= b; 

| inclusive OR operation


class Unique{
  public static boolean isUniqueChar (String str){
    if (str.length() > 256)
      return false;
    boolean[] check = new boolean[256]; // it should be 256 lenght
    for (int i=0; i< str.length(); i++){
      if (check[str.charAt(i)]){
        System.out.println("1.Duplication exists.");
        return false;
      } else{
        check[str.charAt(i)] = true; // set the position of val not i to be true
      }
    }
    System.out.println("1.Every char is unique.");
    return true;
  }
  
  public static boolean isUniqueChar2 (String str){
    if (str.length() > 256)
      return false;
    int check = 0;
    for (int i=0;i<str.length();i++){
      int val = str.charAt(i) - 'a';
      if ( (check & (1<<val))> 0){ // 将1左移val位
        System.out.println("2.Duplication exists.");
        return false;
      } else{
        check |= 1<<val;
      }
    }
    System.out.println("2.Every char is unique.");
    return true;
  }
    
  public static void main(String[] args){
    String str = "abac";
    isUniqueChar(str);
    isUniqueChar2(str);
  }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值