题目描述
输入两个字符串S和L,都只包含英文小写字母。S长度<=100,L长度<=500,000。判定S是否是L的有效字串。
判定规则:S中的每个字符在L中都能找到(可以不连续),且S在L中字符的前后顺序与S中顺序要保持一致。(例如,S="ace"是L="abcde"的一个子序列且有效字符是a、c、e,而"aec"不是有效子序列,且有效字符只有a、e)
输入描述
输入两个字符串S和L,都只包含英文小写字母。S长度<=100,L长度<=500,000。先输入S,再输入L,每个字符串占一行。
输出描述
S串最后一个有效字符在L中的位置。(首位从0开始计算,无有效字符返回-1)
补充说明
示例1
输入:

ace
abcde

输出:4

示例2
输入:

fgh
abcde

输出:-1


Java 解法:

import java.util.Scanner;
 
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.next(); // 读取第一个字符串到s
        String l = scanner.next(); // 读取第二个字符串到l
        scanner.close();
 
        int lastIdx = -1; // 初始化lastIdx为-1,表示找不到时的返回值
        int m = s.length(); // 获取字符串s的长度
        int n = l.length(); // 获取字符串l的长度
        int toMatch = 0;   // 初始化要匹配的位置为0
 
        // 遍历字符串l
        for (int i = 0; i < n; i++) {
            if (toMatch < m && s.charAt(toMatch) == l.charAt(i)) { // 如果当前字符匹配
                toMatch++; // 增加匹配的位置
                lastIdx = i; // 更新最后匹配的索引
            }
            if (toMatch >= m) break; // 如果全部字符都已匹配,则退出循环
        }
 
        System.out.println(lastIdx);
    }
}

Python 解法:

def main():
    s = input()
    l = input()
    # 初始化last_idx为-1,表示找不到时的返回值
    last_idx = -1
    # 初始化匹配位置为0
    to_match = 0
    m = len(s)
    n = len(l)

    # 遍历字符串l
    for i in range(n):
        if to_match < m and s[to_match] == l[i]:
            # 增加匹配的位置
            to_match += 1
            # 更新最后匹配的索引
            last_idx = i
        if to_match >= m:
            break
    print(last_idx)

if __name__ == "__main__":
    main()

C++ 解法:

#include <iostream>
#include <string>
using namespace std;

int main(){
    string s, l;
    cin >> s >> l;     // 从标准输入读取两个字符串到s和l
    int last_idx = -1; // 初始化last_idx为-1,表示找不到时的返回值
    int m = s.length(); // 计算字符串s的长度
    int n = l.length(); // 计算字符串l的长度
    int to_match = 0;   // 初始化匹配的位置为0

    // 遍历字符串l
    for (int i = 0; i < n; i++) {
        if (s[to_match] == l[i])
            to_match++, last_idx = i; // 增加匹配位置,更新最后匹配的索引
        if (to_match >= m) break; // 如果全部字符都已匹配,则退出循环
    }

    cout << last_idx;
    return 0;
}

+++================================================+++
以上内容仅为个人学习记录使用。
如有转载,请附有原文出处链接。

牛客网原文地址:https://www.nowcoder.com/discuss/634152267439951872?sourceSSR=search

posted on 2024-06-28 10:41  Hy旧人伤  阅读(247)  评论(0)    收藏  举报