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