LeetCode刷題記錄(第一天)
原題目:
You're given strings J
representing the types of stones that are jewels, and S
representing the stones you have. Each character in S
is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J
are guaranteed distinct, and all characters in J
S
are letters. Letters are case sensitive, so "a"
is considered a different type of stone from "A"
.翻譯:
你有一個J
代表珠寶和石頭型別的字串,並且S
代表你擁有的寶石。每個S的元素
都是你擁有的一種石頭。你想知道你有多少寶石。
在這些信件J
是保證不同,而在所有的字元J
和S
是字母。字母區分大小寫,因此"a"
被認為是不同型別的石頭"A"
。(直接網頁翻譯......)
自己解釋:
一個字串J,裡面是字母組成,有的字母可以代表寶石,有的只是石頭;是不是寶石取決於字串S中是否包含J中的元素。(區分大小寫!區分大小寫!
事例:
思路: 1、遍歷s;
2、遍歷j;
3、統計s中每個字母在j中出現的次數。
程式碼實現:
package com.mianshi.suanfa.JewelsAndStones; /** * Created by macbook_xu on 2018/3/19. */ public class FindJewels { public static int findJewels(String j,String s){ int num = 0; for (char newS : s.toCharArray()){ for (char newJ : j.toCharArray()){ if (newS==newJ) num++; } } return num; } public static void main(String[] args) { System.out.print(findJewels("z","ZZZZaaa")); } }
總結:雖然作出了這道leetcode上最簡單的題目,但是兩層迴圈巢狀使用一個一個去判斷對效能還是非常有影響,但是思路還是很清晰的。在網站上看評論區還有其他大神的答案,拿來分享一下!
使用hashset中的contains()方法來判斷是否重複:
public int numJewelsInStones(String J, String S) {
int res = 0;
Set setJ = new HashSet();
for (char j: J.toCharArray()) setJ.add(j);
for (char s: S.toCharArray()) if (setJ.contains(s)) res++;
return res;
}
雖然都是兩遍遍歷,但是沒有巢狀,明顯效率提升很多,但我是小白,並沒有想到,不經常使用set。。。。
還有一個更厲害的程式碼:正則表示式實現:
public int numJewelsInStones(String J, String S) {
return S.replaceAll("[^" + J + "]", "").length();
}
僅需一行程式碼。。。。寶寶都看呆了!!!一開始沒有理解,後來找了正則對應字元含義:[^xyz]表示一個字元,並且這個字元不是x,y,z,直接把不是寶石的字母去掉,替換後的字串則全是寶石,長度就為寶石的數量,真的學到了很多,主要學到了解決問題的思想。
還有很多辦法,希望大家一起思考,以後每天都會去刷題總結,希望大家一起進步,小白第一天就學這麼多了,畢竟還得上班,以後每天更新,我會慢慢從leetcode中easy做到hard,每天做多少分享多少,每週更新一次GitHub,放上解決原始碼,謝謝閱讀。