</pre><pre name="code" class="java">/****************************************************************************************
*题目:实现一个算法,确定一个字符串的所有字符是否都不同。假设不允许使用其他的数据结构
*时间:2015年10月12日20:06:13
*文件:DiffChar.java
*作者:cutter_point
****************************************************************************************/
package bishi.Offer50.y2015.m10.d12;
public class DiffChar
{
public boolean diff(String s)
{
if(s == null || s == "")
return true;
//我们通过这个数组进行判断是否存在
boolean sc[] = new boolean[256];
for(int i = 0; i < s.length(); ++i)
{
char c = s.charAt(i);
if(sc[c] == true)
{
//如果已经存在了
return false;
}//if
sc[c] = true;
}//for
return true;
}
/**
* 假设我们的字符只有a-z,那么我们也可以通过位运算实现
* @param str
* @return
* @throws Exception
*/
public boolean isUniqueChars(String str) throws Exception
{
if(str.length() > 26 || str == null)
{
//如果字符数量超过a-z的总数,那么就一定有重复
return false;
}//if
int checkchar = 0; //首先是26个0,也即是一个都没有出现过
//遍历所有的字符
for(int i = 0; i < str.length(); ++i)
{
if(str.charAt(i) < 'a' || str.charAt(i) > 'z')
{
throw new Exception("字符串不和要求");
}//if
//取得这个字符的位置数
int num = str.charAt(i) - 'a';
//我们判断checkchar中是否含有这个字符的位置
if((checkchar & (1 << num)) == 1)
{
//判断,如果是1&1的话,结果就是1,就是存在重复
return false;
}//if
//把这个位置设置为1
checkchar = checkchar | (1 << num);
}//for
return true;
}
public static void main(String[] args) throws Exception
{
Character c = 'c';
String s[] = {"", null, "1213", "abc", "aaaaa", "jksg", "asdasdqc"};
DiffChar d = new DiffChar();
for(int i = 0; i < s.length; ++i)
System.out.println(d.diff(s[i]));
String s2[] = {"avsdf","aaaa","ashdahihsa","123"};
System.out.println("======================");
for(int i = 0; i < s2.length; ++i)
System.out.println(d.isUniqueChars(s2[i]));
}
}
输出:
true
true
Exception in thread "main" false
true
false
true
false
======================
true
false
false
java.lang.Exception: 字符串不和要求
at bishi.Offer50.y2015.m10.d12.DiffChar.isUniqueChars(DiffChar.java:51)
at bishi.Offer50.y2015.m10.d12.DiffChar.main(DiffChar.java:79)