概述
package string;
/**
* 字符串中的第一个唯一字符
* 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
* <p>
* 示例:
* <p>
* s = "leetcode"
* 返回 0
* <p>
* s = "loveleetcode"
* 返回 2
*
* <p>
* 提示:你可以假定该字符串只包含小写字母。
* <p>
* 作者:力扣 (LeetCode)
* 链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xn5z8r/
* 来源:力扣(LeetCode)
* 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
*/
public class OnlyOneCharacter {
public static void main(String[] args) {
String str = "loveleetcode";
//String str = "leetcode";
//int firstUniqueCharIndex = firstUniqueCharNew2(str);
int firstUniqueCharIndex = firstUniqueCharNew3(str.toCharArray());
System.out.println("firstUniqueChar index " + firstUniqueCharIndex);
}
// 超时答案
private static int firstUniqueChar(char[] chars) {
if (chars == null || chars.length == 0) {
return -1;
}
if (chars.length == 1) {
return 0;
}
for (int i = 0; i < chars.length; i++) {
int sameAfterCount = 0;
for (int j = i + 1; j < chars.length; j++) {
if (chars[i] == chars[j]) {
sameAfterCount++;
}
}
int sameBeforeCount = 0;
for (int k = 0; k < i; k++) {
if (chars[k] == chars[i]) {
sameBeforeCount++;
}
}
if (sameAfterCount == 0 && sameBeforeCount == 0) {
return i;
}
}
return -1;
}
// 稍微好些
// 18ms 内存39M
private static int firstUniqueCharNew(char[] chars) {
if (chars == null || chars.length == 0) {
return -1;
}
if (chars.length == 1) {
return 0;
}
int[] counts = new int[26];
for (int i = 0; i < chars.length; i++) {
int pos = chars[i] - 'a';
counts[pos]++;
}
char firstUniqueChar = chooseFirstChar(chars, counts);
if (firstUniqueChar == 0) {
return -1;
}
for (int i = 0; i < chars.length; i++) {
if (chars[i] == firstUniqueChar) {
return i;
}
}
return -1;
}
private static char chooseFirstChar(char[] chars, int[] counts) {
char firstUniqueChar = 0;
for (int m = 0; m < chars.length; m++) {
for (int n = 0; n < counts.length; n++) {
if (counts[n] == 1 && chars[m] == (char) ('a' + n)) {
firstUniqueChar = chars[m];
return firstUniqueChar;
}
}
}
return firstUniqueChar;
}
//方法二:利用已有API,有点投机取巧
//执行32ms 内存38.6M
private static int firstUniqueCharNew2(String chars) {
if (chars == null || chars.length() == 0) {
return -1;
}
for (int i = 0; i < chars.length(); i++) {
char ch = chars.charAt(i);
if (chars.indexOf(ch) == chars.lastIndexOf(ch)) {
return i;
}
}
return -1;
}
// 方法三:先按照从[a-z]统计字符出现的次数 然后遍历字符数组 在统计次数数组中查找首个数组内容为1的,如果是1,则该字符就是要查找的字符
// 这个是最厉害的,耗时4ms 内存49M
private static int firstUniqueCharNew3(char[] chars) {
int[] counts = new int[26];
for (int index = 0; index < chars.length; index++) {
int countIndex = chars[index]-'a';
counts[countIndex]++;
}
for (int n =0; n< chars.length; n++){
// 从counts中取出对应的次数 如果是1 就是该唯一字符了
int countIndex = chars[n]-'a';
if (counts[countIndex] ==1){
return n;
}
}
return -1;
}
}
最后
以上就是有魅力哑铃为你收集整理的011-leetcode-字符串中获取首个唯一不重复的字符的全部内容,希望文章能够帮你解决011-leetcode-字符串中获取首个唯一不重复的字符所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复