請問各位大大,該如何寫呢?謝謝。
設計一個isSubstring函數,給予兩個字串s1 and s2,函數會檢查s1是
否為s2的子字串。假如是,回傳1,否則回傳0。
Examples :
Input : s1 = “row", s2 = “tomorrow"
Output : 1
Input : s1 = "practice", s2 = "tomorrow "
Output : 0.
這樣 ?
# python
def isSubstring(s1, s2):
return 1 if s1 in s2 else 0
# 自刻的話...
def isSubstring(s1, s2):
if len(s1) > len(s2): return 0
for i in range(len(s2)):
for j in range(i, len(s2)):
if s1 == s2[i:j+1]:
return 1
return 0
/** C */
int isSubstring(char* s1, char* 2)
{
return strstr(s2, s1) != NULL ? 1 : 0;
}
/** C 找了範例直接改... */
int isSubstring(char *s1, char *s2)
{
while (*s2)
{
char *Begin = s2;
char *pattern = s1;
// If first character of sub string match, check for whole string
while (*s2 && *pattern && *s2 == *pattern)
{
s2++;
pattern++;
}
// If complete sub string match, return starting address
if (!*pattern)
return 1;
s2 = Begin + 1; // Increament main string
}
return 0;
}
set "row" to s1
set length of s1 to len1
set "tomorrow" to s2
set length of s2 to len2
set 0 to result
if len1 > len2
set 0 to result
else
for i = 1 to len2-len1+1
extract s2 range from char at position i to char at position (i+len1-1) to str
if str equals to s1 then
set 1 to result
end if
end for
end if
write result to output