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();
    }
    正则表达式[^>]表示非>的字符
  • 相关阅读:
    图片延迟加载(lazyload)的实现原理
    jquery lazyload延迟加载技术的实现原理分析
    目前为止用过的最好的Json互转工具类ConvertJson
    ASP.NET前台代码绑定后台变量方法总结
    使用MySql时会遇到中文乱码的问题
    asp.net 时间格式大全
    asp.net 记录用户打开和关闭页面的时间
    分页 排序 表格 多功能
    使用Jquery实现可编辑的表格 并使用AJAX提交到服务器修改数据
    Hive和Hbase
  • 原文地址:https://www.cnblogs.com/ZoHy/p/12400646.html
Copyright © 2011-2022 走看看