我正在解决有关leetcode的以下问题: https://leetcode.com/problems/first-unique-character-in-a-string/description/
我用下面的代码花了39毫秒解决了这个问题:
class Solution {
public int firstUniqChar(String s) {
int[] counter = new int[26];
for(int i=0; i<s.length(); i++)
counter[s.charAt(i)-'a']++;
for(int i=0; i<s.length(); i++){
if(counter[s.charAt(i)-'a'] == 1)
return i;
}
return -1;
}
}
我检查了其他解决方案,发现以下解决方案花费了26毫秒。
class Solution {
public int firstUniqChar(String s) {
int[] count = new int[26];
for(int i = 0; i < s.length(); i++) count[s.charAt(i) - 'a']++;
for(int i = 0; i < s.length(); i++) if(count[s.charAt(i) - 'a'] == 1) return i;
return -1;
}
}
如您所见,唯一的区别是第二种解决方案使用的代码行更少。性能差异来自何处?