第一个只出现一次的字符(Java实现)

来源:互联网 发布:魔兽世界完整剧情知乎 编辑:程序博客网 时间:2024/06/11 04:55

本题为剑指offer面试题35


牛客网测试地址:https://www.nowcoder.com/questionTerminal/1c82e8cf713b4bbeb2a5b31cf5b0417c

  • 时间限制:1秒空间限制:32768K
  •  算法知识视频讲解
在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置。如果字符串为空,返回-1

package go.jacob.day509;/* * 字符char的范围是-128到127,不仅仅是a-z */public class Demo2 {public int FirstNotRepeatingChar(String str) {if (str == null || str.equals(""))return -1;char[] chars = str.toCharArray();int[] arr = new int[256];for (int i = 0; i < chars.length; i++)arr[hash(chars[i])]++;int index = 0;for (int i = 0; i < chars.length; i++) {if (arr[hash(chars[i])] == 1) {index = i;break;}}return index;}// 为字符建立哈希映射,映射数组的下标private int hash(char c) {return c + 128;}}



0 0
原创粉丝点击