LeetCode:Is Subsequence

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 tt 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:
s = "abc"t = "ahbgdc"

Return true.

Example 2:
s = "axc"t = "ahbgdc"

Return false.

给出字符串s和字符串t,检查字符串s是否为t的子序列,假设两个字符串中均为小写字母。所谓子序列,即在原字符串中,去除某些位的字符,剩下的字符保持相对顺序不变,则形成原字符串的字序列。

解题思路1:

利用两个指针,一个指针1指向字符串s的首字符,一个指针2指向t的首字符,接下来进行遍历,若当前位置两个指针所指字符相等,则同时移动两个指针指向下一个字符,否则,只移动指向原字符串的指针,同时注意判断指针1是否到达字符串s的末尾,若是,则范围true。

代码如下:

public class Solution {
    public boolean isSubsequence(String s, String t) {
        if (s.length() == 0) return true;
        int indexS = 0, indexT = 0;
        while (indexT < t.length()) {
            if (t.charAt(indexT) == s.charAt(indexS)) {
                indexS++;
                if (indexS == s.length()) return true;
            }
            indexT++;
        }
        return false;
    }
}


解题思路2:

利用Java的String提供的indexOf(char c, int index)方法,获取从index位置开始,字符c在字符串中的位置,若找不到则返回-1;经过测试,性能比使用双指针的方法更好。

代码如下:

public class Solution 
{
    public boolean isSubsequence(String s, String t) 
    {
        if(t.length() < s.length()) return false;
        int prev = 0;
        for(int i = 0; i < s.length();i++)
        {
            char tempChar = s.charAt(i);
            prev = t.indexOf(tempChar,prev);
            if(prev == -1) return false;
            prev++;
        }
        
        return true;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章