问题:
package com.example.demo; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class Test387 { /** * 方法一:借助set */ public int firstUniqChar(String s) { if (s == null || s.length() == 0) { return -1; } Map<String, Integer> map = new HashMap<>(); for (int i = 0; i < s.length(); i++) { String sub = s.substring(i, i + 1); map.put(sub, map.getOrDefault(sub, 0) + 1); } for (int i = 0; i < s.length(); i++) { String sub = s.substring(i, i + 1); if (map.get(sub) == 1) { return i; } } return -1; } /** * 方法二:利用桶站位 * 问题提示:都是小写字母,所以新建的数据也就是26个长度 */ public int firstUniqChar1(String s) { int len = s.length(); int[] bucket = new int[26]; for (int i = 0; i < len; i++) { char c = s.charAt(i); bucket[c - ‘a‘]++; } for (int i = 0; i < len; i++) { char c = s.charAt(i); if(bucket[c - ‘a‘] == 1){ return i; } } return -1; } public static void main(String[] args) { Test387 t = new Test387(); int asdad = t.firstUniqChar1("asdad"); System.out.println(asdad); } }
原文地址:https://www.cnblogs.com/nxzblogs/p/11274542.html
时间: 2024-10-09 01:27:37