首页 > 代码库 > LeetCode 387 First Unique Character in a String

LeetCode 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.

 

思路:

可以利用两个HashSet,第一个放置出现一次的字符, 第二个放置出现一次的字符,将字符串分放于两个set中之后,根据第一个set的情况来返回相应的下标。或者也可以将字符作为键,出现次数作为值,利用一个HashMap存储,最后找到第一个值为1的键的对应下标即可,二者其实大同小异。

 

解法:

HashSet法

 1 import java.util.Set; 2  3 public class Solution 4 { 5     public int firstUniqChar(String s) 6     { 7         Set<Character> onceSet = new HashSet<>(); 8         Set<Character> multipleSet = new HashSet<>(); 9         int sign = -1;10         char[] sArray = s.toCharArray();11 12         for(int i = 0; i < sArray.length; i++)13         {14             if(multipleSet.contains(sArray[i]))15                 continue;16             else if(onceSet.contains(sArray[i]))17             {18                 onceSet.remove(sArray[i]);19                 multipleSet.add(sArray[i]);20             }21             else22                 onceSet.add(sArray[i]);23         }24 25         if(!onceSet.isEmpty())26         {27             for(int i = 0; i < sArray.length; i++)28             {29                 if(onceSet.contains(sArray[i]))30                 {31                     sign = i;32                     break;33                 }34             }35         }36 37         return sign;38     }39 }

 

HashMap法:

 1 import java.util.Map; 2  3 public class Solution 4 { 5     public int firstUniqChar(int s) 6     { 7         Map<Character, Integer> hashmap = new HashMap<>(); 8         int flag = -1; 9         char[] sArray = s.toCharArray();10 11         for(int i = 0; i < sArray.length; i++)12         {13             if(! hashmap.containsKey(sArray[i]))14                 hashmap.put(sArray[i], 1);15             else16                 hashmap.put(sArray[i], hashmap.get(sArray[i]) + 1);17         }18 19         if(! hashmap.containsValue(1))20             flag = -1;21         else22         {23             for(int i = 0; i < sArray.length; i++)24             {25                 if(hashmap.get(sArray[i]) == 1)26                 {27                     flag = i;28                     break;29                 }30             }31         }32 33         return flag;        34     }35 }

 

LeetCode 387 First Unique Character in a String