【Leetcode做題記錄】9. 回文數(shù),344. 反轉(zhuǎn)字符串,387. 字符串中的第一個(gè)唯一字符

9. 回文數(shù)

題目描述及官方解讀: https://leetcode-cn.com/problems/palindrome-number/solution/

一開(kāi)始只想到轉(zhuǎn)為字符串再判斷

class Solution {
    public boolean isPalindrome(int x) {
        if(x==0){
            return true;
        }
        String a = String.valueOf(x);
        if (a.equals(f(a))) {
            return true;

        } else {
            return false;
        }
    }

    public static String f(String s) {
          if(s==null||s.length()<=1){
            return s;
        }
           return f(s.substring(1)) + s.charAt(0);
    }
}

344. 反轉(zhuǎn)字符串

題目描述: https://leetcode-cn.com/problems/reverse-string/

編寫(xiě)一個(gè)函數(shù),其作用是將輸入的字符串反轉(zhuǎn)過(guò)來(lái)。

示例 1:
輸入: "hello"
輸出: "olleh"
示例 2:
輸入: "A man, a plan, a canal: Panama"
輸出: "amanaP :lanac a ,nalp a ,nam A"

此題實(shí)現(xiàn)思路總體分兩種,遞歸與從后往前遍歷

思路1:遍歷
class Solution {
    public String reverseString(String s) {
        if (s == null||s.length()==0) {
            return "";
        }
        char[] c = new char[s.length()];
        int f = 0;
        for (int i = s.length() - 1; i > -1; i--) {
            c[f++] = s.charAt(i);
        }
        return new String(c);
    }
}

可使用charAt() 或 將字符串轉(zhuǎn)化為字符數(shù)組。

思路2:遞歸

這里要注意遞歸的終止條件,當(dāng)僅剩余一個(gè)字符時(shí),返回該字符本身

 public static String reverseString(String s) {
        if(s==null||s.length()<=1){
            return s;
        }
        return reverseString(s.substring(1)) + s.charAt(0);
    }

387. 字符串中的第一個(gè)唯一字符

題目描述:https://leetcode-cn.com/problems/first-unique-character-in-a-string/

給定一個(gè)字符串,找到它的第一個(gè)不重復(fù)的字符,并返回它的索引。如果不存在,則返回 -1。
案例:
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.

思路1:使用Hashmap

遍歷第一遍:將字符作為Key,value用來(lái)記錄是否出現(xiàn)過(guò)。
遍歷第二遍:輸出第一個(gè)未出現(xiàn)第二遍的字符

class Solution {
    public int firstUniqChar(String s) {
        Map<Character,Integer> map = new HashMap<>();
        for(Character c:s.toCharArray()){
            if(map.containsKey(c)){
                map.put(c,map.get(c)+1);
            }else {
                map.put(c,1);
            }
        }
        for(int i=0;i<s.length();i++){
            if(map.get(s.charAt(i))==1){
                return i;
            }
        }
        return -1;
    }
}
思路2:由于范圍是小寫(xiě)字母,可以用數(shù)組來(lái)記錄每個(gè)字符的出現(xiàn)次數(shù)

也是遍歷兩遍,一遍記錄,一遍用來(lái)輸出第一個(gè)出現(xiàn)一次的字符。

class Solution {
    public int firstUniqChar(String s) {
        int[] word = new int[26];
        for(int i = 0; i < s.length(); i++){
            word[s.charAt(i)-'a']++;
        }
        for(int i = 0; i < s.length(); i++){
            if(word[s.charAt(i)-'a']==1)
                return i;
        }
        return -1;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容