字符串分割匹配

leetcode 139. Word Break

一、问题描述

给定一个非空字符串s和一个包含非空单词列表的字典wordDict,确定s是否可以分割为一个或多个字典单词的空格分隔序列。
注意:
1)字典中的相同单词可能会在分段中重复使用多次。
2)假设字典中不包含重复的单词。
【举例】
<例 1>
输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true

<例 2>
输入: s = "applepenapple", wordDict = ["apple", "pen"]
输出: true

<例 3>
输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
输出: false

二、解题思路

设f(i)表示s[0,,,i]是否可被分割---即s中长度为i的子串能否被分割
    状态转移方程为:
    f( i ) = f( j ) && s[ j+1 , i ] ∈ dict
    边界:空串视为可以分割---f(0)=true

三、解题算法

/****************************************************
Author:tmw
date:2018-5-29
****************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

//截取子串
char* substr(char* str, int i, int len)
{
    int m;
    int k=0;
    char* temp=(char*)malloc(strlen(str)*sizeof(char));
    for(m=i;m<len;m++)
        temp[k++] = str[m];
    temp[k]='\0';

    return temp;
}

//截取的子串与dict中的所有字符串匹配
bool find_str(char* str, char** wordDict, int wordDictSize)
{
    int i;
    for(i=0; i<wordDictSize; i++)
    {
        if( strcmp(str,wordDict[i])==0 )
            return true;
    }

    return false;
}

bool wordBreak(char* s, char** wordDict, int wordDictSize)
{
    int i,j;
    int len_s = strlen(s);

    bool f[len_s+1];
    for(i=0; i<len_s+1; i++) f[i]=false;


    f[0] = true;

    for( i=1; i<=len_s; i++ )
    {
        for( j=i-1; j>=0; j-- )
        {
            if( f[j] && find_str( substr(s,j,i), wordDict, wordDictSize ) )
            {
                f[i] = true;
                break;
            }
        }
    }

    return f[len_s];
}

四、执行结果

leetcode accept


梦想还是要有的,万一实现了呢~~~~ヾ(◍°∇°◍)ノ゙~~~~


猜你喜欢

转载自blog.csdn.net/qiki_tangmingwei/article/details/80543192
今日推荐