码迷,mamicode.com
首页 > 其他好文 > 详细

CC150-Array and string 1.1

时间:2015-08-15 01:29:27      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

Promble:

Implement an algorithm to determine if a string has all unique characters. What if you cannot use addtional data structure?

My solution:

1.ckeck wether the length of str is really equal to 0 or more than 256, if yes, it will return false

2. ASCII have 256 character

3 . use ToArray function chage string as char array

4. sort char array

5. compare between two character, get duplicate or not

code: 

public static boolean different(String str){
if(str.length()==0||str==null||str.length()>256) return false;
char[] strlist = str.toCharArray();
Arrays.sort(strlist);
for(int i= 1; i<strlist.length; i++){
if(strlist[i]==strlist[i-1])
return true;
}
return false;
}

 

The given solution:

1. build a boolean Array and record the character appear on the string according the ASCII value 

2. if corresponding ASCII value is exist, then return false.

code:

public static boolean isUniqueChars2(String str){

if(str.length()==0||str.length()>256) return false;

boolean[] char_set = new boolean[256];

for(int i =0 ; i < str.length();i++){

int value = str.charAt(i)

if(char_set[value]){

return false;

}

char_set[value]=true;

}

return true;

}

CC150-Array and string 1.1

标签:

原文地址:http://www.cnblogs.com/whaochen/p/4731588.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!