Leetcode One Question of the Day: 925.Long Pressed Name (Long Pressed Name)

Insert picture description here
The general meaning is the typed对应位置上的相同字符数要大于等于name对应位置上的字符
idea: double pointer traversal, each time find out the number of characters in the corresponding position, and then compare, be careful not to forget the problem of the typed string is too long;
Insert picture description here

bool isLongPressedName(string name, string typed)
{
    
    
    //双指针遍历两个字符串
    int p1 = 0, p2 = 0;
    int len1 = name.size(), len2 = typed.size();
    if (len1 == 0 && len2 == 0)
    {
    
    
        return true;
    }
    if (len1 == 0 && len2 > 0)
    {
    
    
        return false;
    }
    //只要name没被遍历完,就继续执行
    while (p1 < len1)
    {
    
    
        char c = name[p1];
        int count1 = 0;
        while (p1 < len1 && name[p1] == c)
        {
    
    
            p1++;
            count1++;
        }

        int count2 = 0;
        while (p2 < len2 && typed[p2] == c)
        {
    
    
            p2++;
            count2++;
        }
        if (count2 < count1)//如果typed中没有该字符或者该字符个数比name中对应位置的少,直接return false
        {
    
    
            return false;
        }
    }
    if (p2 != len2)//如果typed后面还有多余字符
    {
    
    
        return false;
    }
    return true;
}

Guess you like

Origin blog.csdn.net/wyll19980812/article/details/109195896