国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

LeetCode387 First Unique Character in a String

2019-11-08 20:17:27
字體:
供稿:網(wǎng)友

題目

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 = “l(fā)eetcode” return 0.

s = “l(fā)oveleetcode”, return 2. Note: You may assume the string contain only lowercase letters. 即找到字符串中第一個不重復(fù)的字母。

方法一

很自然的想到兩次遍歷來找到唯一的字符,同時利用字母只有26個的特點減少循環(huán)次數(shù)。

public int firstUniqChar(String s) { if (s.length() == 0) return -1; int[] test = new int[s.length()]; int count = 0; int result = -1; boolean found = true; for (int i = 0; i < s.length() && count < 27; i++) { if (test[i] == 1) continue; else count++; for (int j = i + 1; j < s.length(); j++) { if (test[j] == 1) continue; if (s.charAt(i) == s.charAt(j)) { found = false; test[i] = 1; test[j] = 1; } } if (found) { result = i; break; } found = true; } return result; }

方法二

嵌套循環(huán)毫無疑問效率低下,這是想到使用鍵值對記錄每個字母的出現(xiàn)次數(shù),同時利用hashmap去重的特性。

public int firstUniqChar1(String s) { if (s.length() == 0) return -1; int result = -1; Map<Character, Integer> map = new HashMap<>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (map.containsKey(c)) map.put(c, map.get(c) + 1); else map.put(c, 1); } for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (map.get(c) == 1) { result = i; break; } } return result; }

雖然簡化了步驟,但是map的使用仍然需要較多的時間開銷。這是可以使用數(shù)組的1~26個位置代表a~z出現(xiàn)的次數(shù)。

public int firstUniqChar2(String s) { if (s.length() == 0) return -1; int result = -1; int[] record = new int[26]; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); int index = c - 'a'; record[index]++; } for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (record[s.charAt(i)-'a'] == 1) { result = i; break; } } return result; }
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 永宁县| 饶阳县| 中宁县| 碌曲县| 运城市| 建始县| 桃园县| 东方市| 农安县| 苍溪县| 海安县| 上杭县| 北海市| 恭城| 稷山县| 临西县| 东平县| 横峰县| 张北县| 夏河县| 石城县| 靖州| 诸城市| 沅江市| 新宾| 灯塔市| 西平县| 普定县| 平利县| 黔南| 香河县| 玉门市| 温宿县| 萝北县| 桓仁| 慈利县| 东安县| 墨玉县| 奉贤区| 寿光市| 鄢陵县|