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:
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;
}
}