LeetCode--No.771-Jewels and Stones


雖然是很簡單的題,但是發現一個問題。

就是如何遍歷一個String更好一點

class Solution {
    public int numJewelsInStones(String J, String S) {
        if (J == null || S == null)     return 0;
        Set<Character> set = new HashSet<>();
        for(int i = 0; i < J.length(); i++){
            set.add(J.charAt(i));
        }
        int res = 0;
        for(int i = 0; i < S.length(); i++){
            if (set.contains(S.charAt(i)))
                res++;
        }
        return res;
    }
}

我是一個一個遍歷,然後再把當前字符轉化成char. 下面是copy別人的數組,S.toCharArray() 感覺更好。

public int numJewelsInStones(String J, String S) {
    int[] jewels = new int[58];
    for(char j: J.toCharArray()) {
      jewels[j - 'A'] = 1;
    }

    int count = 0;
    for(char s: S.toCharArray()) {
      count = count + jewels[s - 'A'];
    }
    return count;
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章