9. 回文數(shù)
題目描述及官方解讀: https://leetcode-cn.com/problems/palindrome-number/solution/
一開始只想到轉(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/
編寫一個函數(shù)椭蹄,其作用是將輸入的字符串反轉(zhuǎn)過來镊绪。
示例 1:
輸入: "hello"
輸出: "olleh"
示例 2:
輸入: "A man, a plan, a canal: Panama"
輸出: "amanaP :lanac a ,nalp a ,nam A"
此題實現(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:遞歸
這里要注意遞歸的終止條件产还,當僅剩余一個字符時部凑,返回該字符本身
public static String reverseString(String s) {
if(s==null||s.length()<=1){
return s;
}
return reverseString(s.substring(1)) + s.charAt(0);
}
387. 字符串中的第一個唯一字符
題目描述:https://leetcode-cn.com/problems/first-unique-character-in-a-string/
給定一個字符串蘸吓,找到它的第一個不重復的字符,并返回它的索引。如果不存在库继,則返回 -1葬燎。
案例:
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.
思路1:使用Hashmap
遍歷第一遍:將字符作為Key,value用來記錄是否出現(xiàn)過。
遍歷第二遍:輸出第一個未出現(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:由于范圍是小寫字母拌汇,可以用數(shù)組來記錄每個字符的出現(xiàn)次數(shù)
也是遍歷兩遍柒桑,一遍記錄,一遍用來輸出第一個出現(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;
}
}