LeetCode:判断s字符串是否为t字符串的子序列

Given a string s and a string t,check if s is subsequence of t.
You may assume that there is only lower case English letters in both s and t.t is
potentially a very long(length-=500,000)string and s is a short string(<=100).
A subsequence of a string is a new string which is formed from the original string
by deleting some(can be none)of the characters without disturbing the relative
positions of the remaining characters.(ie,"ace" is a subsequence of "abcde" while
"aec" is not).

Example 1:
Input:s="abc",t="ahbgdc"
Output:true

Example 2:
Input:s="axc",t="ahbgdc"
Output:false

题目大意:
给定字符串s和t,判断s是否为t的子序列,这个子序列是原始字符串删除一些(或者不删除)的字符而不改变剩余字符
相对位置形成的新字符.

解题思路:
方法1:
可以直接使用贪心算法.注意需要保持s字母的顺序.

Go语言实现 

package main

import "fmt"

func isSubsequence(s,t string)bool{
	if len(s)==0{
		return true
	}
	ans,i,j:=false,0,0
	for ;i<len(t)&&j<len(s);i++{
		if t[i]==s[j]{
			j++
		}
		if j>=len(s){
			return true
		}
	}
	return ans
}

func IsSubsequence(s,t string)bool{
	for len(s)>0&&len(t)>0{
		if s[0]==t[0]{
			s=s[1:]
		}
		t=t[1:]
	}
	return len(s)==0
}

func IsSub(s,t string)bool{
	index,flag:=0,false
	for i:=0;i<len(s);i++{
		flag=false
		for ;index<len(t);index++{
			if s[i]==t[index]{
				flag=true
				break
			}
		}
		if flag==true{
			index++
			continue
		}else{
			return false
		}
	}
	return true
}
func main(){
	s,t:="abc","ahbgdc"
	fmt.Println(isSubsequence(s,t))
}

C++语言实现

#include <iostream>
#include <string>

using namespace std;
class Solution{
public:
    bool isSubsequence(string s,string t){
        while(!s.empty()&&!t.empty()){
            if(s[0]==t[0]){
                s=s.substr(1);
            }
            t=t.substr(1);/*或者用t.erase(0,1)即可,删除第一个字符*/
        }
        return s.empty();
    }
};
int main(int argc,char* argv[]){
    string s="abe",t="ahbgcd";
    cout<<Solution().isSubsequence(s,t)<<endl;
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路上的追梦人

您的鼓励就是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值