如何加快第一个唯一字符查找

编程入门 行业动态 更新时间:2024-10-16 22:15:18
本文介绍了如何加快第一个唯一字符查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在解决

是否有一些技巧可以提高LeetCode得分?似乎增强型 for-each 循环的性能比标准 for 循环要好,但我无法证明这一点,

解决方案

我得到 98.58 %的内容是:-

public int firstUniqChar(String s){ int count [] = new int [122-96]; final char [] chars = s.toCharArray(); for(int i = 0; i< chars.length; i ++){ count [chars [i]-97] ++; } for(int i = 0; i< chars.length; i ++){ if(count [chars [i]-97] == 1)返回一世; } 返回-1; }

I'm solving 387. First Unique Character in a String LeetCode problem defined as:

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.

Taking advantage of the input being fully lowercase ASCII I created two bit vectors to track when we encounter a character for the first and second time.

Can below code be improved further? LeetCode says that below code is better than 94.33% solutions. What else could have been done by the last 5.67% solutions that they were better?

class Solution { public int firstUniqChar(String s) { int firstSpot = 0; int secondSpot = 0; char[] chars = s.toCharArray(); for (char c : chars) { int mask = 1 << c - 'a'; if ((firstSpot & mask) == 0) { firstSpot |= mask; } else if ((secondSpot & mask) == 0) { secondSpot |= mask; } } int i = 0; for (char c : chars) { int mask = 1 << c - 'a'; if ((secondSpot & mask) == 0) { return i; } i++; } return -1; } }

Are there tricks that can be done to improve the LeetCode score? It seems that enhanced for-each loop performs better than standard for loop but I can't prove it, It's an observation based on few of my previous submissions.

解决方案

I got 98.58% with this:-

public int firstUniqChar(String s) { int count[] = new int[122 - 96]; final char[] chars = s.toCharArray(); for (int i = 0; i < chars.length; i++) { count[chars[i] - 97]++; } for (int i = 0; i < chars.length; i++) { if (count[chars[i] - 97] == 1) return i; } return -1; }

更多推荐

如何加快第一个唯一字符查找

本文发布于:2023-11-29 12:31:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646402.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:第一个   字符

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!