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

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

LeetCode String專題

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

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所在的索引,導致效率不高。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 崇明县| 肇庆市| 博客| 婺源县| 屏东市| 黑龙江省| 洞口县| 明星| 湖州市| 贵港市| 弥勒县| 安新县| 根河市| 岢岚县| 青川县| 莱芜市| 长治县| 乌鲁木齐市| 三穗县| 合山市| 灵石县| 天柱县| 海原县| 双鸭山市| 泸州市| 高台县| 武平县| 沙洋县| 榕江县| 上思县| 兴业县| 金坛市| 尚义县| 白朗县| 油尖旺区| 武威市| 阜康市| 双牌县| 达日县| 镇坪县| 宝山区|