加载中...
1876-长度为三且各字符不同的子字符串(Substrings of Size Three with Distinct Characters)
发表于:2021-12-03 | 分类: 简单
字数统计: 386 | 阅读时长: 1分钟 | 阅读量:

原文链接: https://leetcode-cn.com/problems/substrings-of-size-three-with-distinct-characters

英文原文

A string is good if there are no repeated characters.

Given a string s​​​​​, return the number of good substrings of length three in s​​​​​​.

Note that if there are multiple occurrences of the same substring, every occurrence should be counted.

A substring is a contiguous sequence of characters in a string.

 

Example 1:

Input: s = "xyzzaz"
Output: 1
Explanation: There are 4 substrings of size 3: "xyz", "yzz", "zza", and "zaz". 
The only good substring of length 3 is "xyz".

Example 2:

Input: s = "aababcabc"
Output: 4
Explanation: There are 7 substrings of size 3: "aab", "aba", "bab", "abc", "bca", "cab", and "abc".
The good substrings are "abc", "bca", "cab", and "abc".

 

Constraints:

  • 1 <= s.length <= 100
  • s​​​​​​ consists of lowercase English letters.

中文题目

如果一个字符串不含有任何重复字符,我们称这个字符串为  字符串。

给你一个字符串 s ,请你返回 s 中长度为 3 的 好子字符串 的数量。

注意,如果相同的好子字符串出现多次,每一次都应该被记入答案之中。

子字符串 是一个字符串中连续的字符序列。

 

示例 1:

输入:s = "xyzzaz"
输出:1
解释:总共有 4 个长度为 3 的子字符串:"xyz","yzz","zza" 和 "zaz" 。
唯一的长度为 3 的好子字符串是 "xyz" 。

示例 2:

输入:s = "aababcabc"
输出:4
解释:总共有 7 个长度为 3 的子字符串:"aab","aba","bab","abc","bca","cab" 和 "abc" 。
好子字符串包括 "abc","bca","cab" 和 "abc" 。

 

提示:

  • 1 <= s.length <= 100
  • s​​​​​​ 只包含小写英文字母。

通过代码

高赞题解

解题思路

此处撰写解题思路
image.png
你有更好的想法,可以分享出来!

代码

class Solution {
    public int countGoodSubstrings(String s) {
        int l=s.length();
        String c="";
        String cc="";
        int lm=0;
        int res=0;
        int rm=lm+3;
        while(rm<=l){
            c=s.substring(lm,rm);
            for(int i=0;i<c.length();i++){
                if(i==0) cc = c.charAt(i)+"";
                else if(cc.contains(c.charAt(i)+"")){
                    break;
                }else{
                    cc += c.charAt(i)+"";
                    continue;
                }
            }
            if(cc.length() == 3)  res++; 
            cc="";
            lm++;
            rm++;
        }
        return res;
    }
}

统计信息

通过次数 提交次数 AC比率
6891 9486 72.6%

提交历史

提交时间 提交结果 执行时间 内存消耗 语言
上一篇:
1857-有向图中最大颜色值(Largest Color Value in a Directed Graph)
下一篇:
1877-数组中最大数对和的最小值(Minimize Maximum Pair Sum in Array)
本文目录
本文目录