本文地址: http://blog.csdn.net/caroline_wendy
ASCII码共有256位,字符异同判断,使用位操作即可解决(11行),位操作还可以排序非重复数字数组(11行).
位是一个二值的存储单元,直接进行操作,用于判断重复和非重复排序,节省时间和空间,可以使用bool数组代替其功能.
代码:
/**
* created by C.L.Wang
*/
public class Main {
public static void main(String[] args) {
String str = "god+byte";
System.out.println("是否唯一: " + isUniqueChars(str));
int[] arr = {4, 5, 1, 6, 3, 2};
sort(arr);
System.out.print("排序数组: ");
for (int i : arr) {
System.out.print(i + " ");
}
}
/**
* 判断字符串中的字符是否唯一
*
* @param str 字符串
* @return 是否唯一
*/
public static boolean isUniqueChars(String str) {
if (str.length() > 256) return false;
boolean[] bs = new boolean[256];
for (int i = 0; i < str.length(); ++i) {
int val = str.charAt(i);
if (bs[val])
return false;
bs[val] = true;
}
return true;
}
/**
* 位排序(无重复数组)
*
* @param arr 待排序数组
*/
public static void sort(int[] arr) {
final int MAX = 256;
boolean[] bs = new boolean[MAX];
for (int i : arr)
bs[i] = true;
int n = 0;
for (int i = 0; i < MAX; ++i) {
if (bs[i])
arr[n++] = i;
}
}
}输出:
是否唯一: true 排序数组: 1 2 3 4 5 6
原文地址:http://blog.csdn.net/caroline_wendy/article/details/45070141