zoukankan      html  css  js  c++  java
  • 771. Jewels and Stones

    You're given strings J representing the types of stones that are jewels, and S representing the stones you have.  Each character in Sis 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 and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A". Example 1:
    Input: J = "aA", S = "aAAbbbb"
    Output: 3
    Example 2:
    Input: J = "z", S = "ZZ"
    Output: 0
    Note:
    • S and J will consist of letters and have length at most 50.
    • The characters in J are distinct.
    题解:
    class Solution {
        public int numJewelsInStones(String J, String S) {
            int sum = 0;
            char ss[] = new char[50];
            ss = S.toCharArray();
            for(char s:ss){
                if(J.indexOf(s)!=-1)
                    sum+=1;
    
            }
            return sum;
            
        }
    }
    这是一道关于字符串的题目,最先想到的做法是把两个字符串拆开两层for循环遍历,在搜索split()方法的时候发现了toCharArray()方法和indexOf(String s) 两个方法 前者可以将字符串转化为字符数组,返回char[] 后者用于判别某字符串是否包含某字串s,若不是返回-1,否则返回其他int
    split()方法
    stringObj.split(String separator,int limit)
    stringObj 
    必选项。要被分解的 String 对象或文字。该对象不会被 split 方法修改。
    
    separator 
    可选项。字符串或 正则表达式 对象,它标识了分隔字符串时使用的是一个还是多个字符。如果忽
    略该选项,返回包含整个字符串的单一元素数组。 
    
    limit
    可选项。该值用来限制返回数组中的元素个数。
    one liner解法:
    public int numJewelsInStones(String J, String S) {
        return S.replaceAll("[^" + J + "]", "").length();
    }
    正则表达式[^>]表示非>的字符
  • 相关阅读:
    意料之外,情理之中,Spring.NET 3.0 版本发布-
    学习究竟是为了什么?
    测量软件应用系统的聚合复杂度【翻译稿】
    关键字New,如阴魂不散
    选择IT事业,意味着终身学习
    华为机试001:字符串最后一个单词的长度(华为OJ001)
    C++版
    C++版
    C++版-剑指offer 面试题6:重建二叉树(Leetcode105. Construct Binary Tree from Preorder and Inorder Traversal) 解题报告
    C++版
  • 原文地址:https://www.cnblogs.com/ZoHy/p/12400646.html
Copyright © 2011-2022 走看看