您的位置:首页 > 产品设计 > UI/UE

lintcode(646)First Position Unique Character

2017-05-13 10:17 309 查看
描述:

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return 
-1
.

样例:

Given s = 
"lintcode"
, return 
0
.

Given s = 
"lovelintcode"
, return 
2
.
思路:

逐个字符遍历,查看以 i 为分割点前后两个字符串是否包含重复字符

或者建立hashmap,存储字符信息

public class Solution {
/**
* @param s a string
* @return it's index
*/
public int firstUniqChar(String s) {
// Write your code here
if(s == null || s.length() == 0){
return -1;
}
for(int i = 0;i<s.length() - 1;i++){
char p = s.charAt(i);
if(s.indexOf(p , i + 1) < 0 && s.indexOf(p) == i){
return i;
}
}
if(s.indexOf(s.charAt(s.length() - 1)) == s.length() - 1){
return s.length() - 1;
}
return -1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: