给定英文句子S和字符串x,判断x是否为S中某些单词的前缀,若匹配到则输出第1个匹配单词的位置,否则输出-1。
例如:输入"this is an easy problem."和"eas",输出4
例如:输入"In love folly is always sweet"和"like",输出-1
例如:输入"Whatever is worth doing is worth doing well."和"wor",输出3
给定英文句子S和字符串x,判断x是否为S中某些单词的前缀,若匹配到则输出第1个匹配单词的位置,否则输出-1。
例如:输入"this is an easy problem."和"eas",输出4
例如:输入"In love folly is always sweet"和"like",输出-1
例如:输入"Whatever is worth doing is worth doing well."和"wor",输出3
"this is an easy problem.","eas"
4
import java.util.*; public class Solution { /** * 在句子中找到前缀是str的首个单词位置 * @param s string字符串 英文句子 * @param x string字符串 字符串 * @return int整型 */ public int match_str_in_sentence (String s, String x) { // write code here if (s.indexOf(x) >= 1) { String[] str = s.split(" "); for (int i = 0; i < str.length; i++) { if(str[i].contains(x)){ return i+1; } } } else { return -1; } return 0; } }
# # 在句子中找到前缀是str的首个单词位置 # @param s string字符串 英文句子 # @param x string字符串 字符串 # @return int整型 # class Solution: def match_str_in_sentence(self , s , x ): # write code here if s=="":return -1 ss=s.split(' ') for i in range(len(ss)): if ss[i].find(x)!=-1: return (i+1) return -1