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

首頁 > 學院 > 開發設計 > 正文

LeetCode String專題

2019-11-14 09:01:36
字體:
來源:轉載
供稿:網友

LeetCode String專題部分,更多說明請見LeetCode Array專題

344. Reverse String

Write a function that takes a string as input and returns the string reversed.

Example: Given s = “hello”, return “olleh”.

譯:實現一個函數可將輸入的字符串翻轉。

實現

public class Solution { public String reverseString(String s) { if (s == null || s.length() == 0) { return ""; } char[] chars = s.toCharArray(); StringBuilder sb = new StringBuilder(); for (int index = s.length() - 1; index >= 0; index--) { sb.append(chars[index]); } return sb.toString(); }}

問題分析

效率有待優化。

387. First Unique Character in a String

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.

譯:給你一個字符串,找出其中第一個沒有重復的字符并返回其索引。如果不存在這樣的字符,返回 -1;

實現

public class Solution { public int firstUniqChar(String str) { if (str == null || str.length() <= 0) { return -1; } char[] charElements = str.toCharArray(); LinkedHashMap<Character, Integer> boxMap = new LinkedHashMap<>(); for (char element : charElements) { if (!boxMap.containsKey(element)) { boxMap.put(element, 1); } else boxMap.put(element, boxMap.get(element).intValue() + 1); } for (char key : boxMap.keySet()) { if (boxMap.get(key) <= 1 && boxMap.get(key) >= 0) { for (int index = 0; index < charElements.length; index++) { if (charElements[index] == key) { return index; } } } } return -1; }}

問題分析

在此我使用的是LinkedHashMap來進行元素的存儲,因為有序,所以避免了順序混亂的問題。在將字符串轉換為char的數組后遍歷一次將每個元素以鍵的形式對應的存在Map的Key中,如果已經存儲過的元素則將其的值Value加一,默認為1。全部存儲過后再進行Map的查找第一個值為1的Key則命中目標。接著我的實現還有待改善,因為套用了嵌套的for循環二次遍歷char數組中該Key所在的索引,導致效率不高。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 高邮市| 绵阳市| 华容县| 林口县| 大连市| 温泉县| 凤庆县| 新和县| 靖宇县| 潞城市| 巫山县| 溧水县| 天长市| 崇仁县| 濉溪县| 阿拉善右旗| 囊谦县| 沙坪坝区| 南靖县| 谷城县| 宝丰县| 云和县| 红河县| 固阳县| 布拖县| 阿克陶县| 荥阳市| 绥宁县| 安阳县| 锡林浩特市| 长宁区| 上高县| 新竹市| 大邑县| 方城县| 都兰县| 浑源县| 浑源县| 临潭县| 汾西县| 公主岭市|