剑指offer--第一个只出现一次的字符

来源:互联网 发布:双色球破解软件 编辑:程序博客网 时间:2024/05/20 11:27

题目描述

在一个字符串(1<=字符串长度<=10000,全部由大写字母组成)中找到第一个只出现一次的字符。


分类:字符串

解法1:使用hashmap,不过因为只是字母,所以可以使用数组代替。
遍历字符,记录下字符出现过的次数,返回次数唯一的字符即可
[java] view plain copy
  1. public class Solution {  
  2.     public int FirstNotRepeatingChar(String str) {  
  3.         if(str.length()==0return -1;      
  4.         int arr[] = new int[26];         
  5.         int mark = -1;  
  6.         char[] chars = str.toCharArray();  
  7.         char temp;  
  8.         if(chars[0]>='a') temp='a';  
  9.         else temp = 'A';  
  10.            
  11.         for(int i=0;i<chars.length;i++){  
  12.           arr[chars[i]-temp]++;            
  13.         }     
  14.         for(int i=0;i<chars.length;i++){  
  15.           if(arr[chars[i]-temp]==1){  
  16.             mark = i;  
  17.             break;  
  18.           }  
  19.         }     
  20.         return mark;  
  21.     }  
  22. }  



原文链接  http://blog.csdn.net/crazy__chen/article/details/45011449

原创粉丝点击