题解 | #字符串字符匹配#[c-'a']++
字符串字符匹配
https://www.nowcoder.com/practice/22fdeb9610ef426f9505e3ab60164c93
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNext()) { // 注意 while 处理多个 case String shortStr = in.nextLine(); String longStr = in.nextLine(); isInclude(shortStr,longStr); } } public static void isInclude(String s,String l){ StringBuilder sb = new StringBuilder(); char sc; for (int i = 0; i < s.length(); i++) { sc= s.charAt(i); //短字符串去重 if(s.indexOf(sc)==i){ sb.append(sc); } } s = sb.toString();//StringBuilder转换为String //使用26字母数组统计两个字符串各个字母的数量,然后两个数组对应字母下标数量相减,一旦出现一个-1就不通过,减完后就说明包含。 int[] letters = new int[26]; char c; for (int i = 0; i < l.length(); i++) { c=l.charAt(i);//c letters[c-'a']++;//letters[2]++ } for (int i = 0; i < s.length(); i++) { c=s.charAt(i); letters[c-'a']--; if(letters[c-'a']<0){ System.out.println(false); return; } } System.out.println(true); } }
多思考了下,前面做题给的灵感,使用数组[c-'a']++的形式统计长字符串的字母,然后遍历短字符串,并且[c-'a']--,如果差值小于0,说明短字符串有字符不在长字符串里面。若是短字符串里面有重复的字符,而长字符串没有重复字符就需要给短字符串去重。因为数组统计的方式字母比较都是一次性的。此方法比较通用,原本就适合那种不去重的原生态比较。