387.求字符串中第一个独立存在的字符 First Unique Character in a String

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

Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

Note: You may assume the string contain only lowercase letters.



  1. public class Solution {
  2. public int FirstUniqChar(string s) {
  3. int index = -1;
  4. char[] chars = s.ToCharArray();
  5. char c = ' ';
  6. int length = chars.Length;
  7. Dictionary<char,int> d = new Dictionary<char,int>();
  8. for(int i =0;i<length;i++){
  9. c = chars[i];
  10. int v = 0;
  11. if(d.TryGetValue(c,out v)){
  12. d[c] = v + 1;
  13. }else{
  14. d.Add(c,1);
  15. }
  16. }
  17. for(int i=0;i<length;i++){
  18. c = chars[i];
  19. if(d[c] == 1){
  20. index = i;
  21. break;
  22. }
  23. }
  24. return index;
  25. }
  26. }





posted @ 2017-01-10 23:05  xiejunzhao  阅读(274)  评论(0编辑  收藏  举报