0

## 請教各位高手,使用C或Python設計一個isSubstring函數，給予兩個字串s1 and s2,函數會檢查s1是否為s2的子字串。

Examples :
Input : s1 = “row", s2 = “tomorrow"
Output : 1
Input : s1 = "practice", s2 = "tomorrow "
Output : 0.

ccutmis iT邦高手 8 級 ‧ 2020-03-25 12:20:04 檢舉

froce iT邦大師 2 級 ‧ 2020-03-25 17:28:04 檢舉

### 2 個回答

1
listennn08
iT邦新手 1 級 ‧ 2020-03-25 13:17:31

``````# 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;
}
``````
1

iT邦大神 1 級 ‧ 2020-03-25 13:22:29
``````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
``````
yiwen6761 iT邦新手 5 級 ‧ 2020-03-26 14:03:31 檢舉