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();
    }
    正则表达式[^>]表示非>的字符
  • 相关阅读:
    主键、外键、复合外键的创建
    DbHelper and OracleHelper
    Oracle 给表添加主键和使ID自增、触发器、创建结构一样的表
    Oracle 参数化更新数据时报错:Oracle ORA-01722: 无效数字
    ASP.NET MVC 基础
    5. CSS新特性之浏览器私有前缀
    JavaScript-----15.简单数据类型和复杂数据类型
    JavaScript-----14.内置对象 Array()和String()
    JavaScript-----13.内置对象 Math()和Date()
    JavaScript-----12.对象
  • 原文地址:https://www.cnblogs.com/ZoHy/p/12400646.html
Copyright © 2011-2022 走看看