Word Break II

本文介绍了一种使用深度优先搜索加记忆化(DFS+Memorization)及动态规划加回溯(DP+Backtrack)的方法来解决给定字符串的拆分问题,通过查找字典中的有效单词来构造合法句子。

Given a string s and a dictionary of words dict, add spaces ins to construct a sentence where each word is a valid dictionary word.

Return all such possible sentences.

For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].

A solution is ["cats and dog", "cat sand dog"].


	// DFS + Memorization
	public ArrayList<String> wordBreak(String s, Set<String> dict) {
		// Note: The Solution object is instantiated only once and is reused by
		// each test case.
		// min and max length of words in dictionary, used for
		// pruning.
		int min = Integer.MAX_VALUE;
		int max = Integer.MIN_VALUE;
		for (String str : dict) {
			min = Math.min(min, str.length());
			max = Math.max(max, str.length());
		}
		Map<String, ArrayList<String>> memorized = new HashMap<String, ArrayList<String>>();
		return wordBreakHelper(s, dict, min, max, memorized);
	}

	private ArrayList<String> wordBreakHelper(String s, Set<String> dict,
			int min, int max, Map<String, ArrayList<String>> memorized) {
		if (memorized.containsKey(s))
			return memorized.get(s);
		ArrayList<String> res = new ArrayList<String>();
		if (s == null || s.length() == 0)
			return res;
		if (dict.contains(s))
			res.add(s);
		// i pruning
		for (int i = min; i <= Math.min(s.length(), max); i++) {
			String prefix = s.substring(0, i);
			if (dict.contains(prefix)) {
				String suffix = s.substring(i);
				List<String> suffixBreak = wordBreakHelper(suffix, dict, min,
						max, memorized);
				if (!suffixBreak.isEmpty()) {
					for (String str : suffixBreak) {
						res.add(prefix + " " + str);
					}
				}
			}
		}
		memorized.put(s, res);
		return res;
	}

	// DP + back track
	public ArrayList<String> wordBreak2(String s, Set<String> dict) {
		int n = s.length();
		ArrayList<ArrayList<Integer>> pres = new ArrayList<ArrayList<Integer>>(
				n);
		// initialize
		for (int i = 0; i < n; ++i)
			pres.add(new ArrayList<Integer>());
		// DP. pres[i] stores position j where should insert space
		for (int i = 0; i < n; ++i) {
			for (int j = 0; j <= i; ++j) {
				String suffix = s.substring(j, i + 1);
				if ((j == 0 || pres.get(j - 1).size() > 0) && dict.contains(suffix))
					pres.get(i).add(j);
			}
		}
		return getPath(s, n, pres);
	}

	public ArrayList<String> getPath(String s, int n, ArrayList<ArrayList<Integer>> pres) {
		ArrayList<String> res = new ArrayList<String>();
		for (int pre : pres.get(n - 1)) {
			if (pre == 0) {
				res.add(s.substring(0, n));
			} else {
				ArrayList<String> preres = getPath(s, pre, pres);
				String sub = s.substring(pre, n);
				for (String ss : preres)
					res.add(ss + " " + sub);
			}
		}
		return res;
	}


给定引用中未提及DT_WORDBREAK的相关信息。DT_WORDBREAK是Windows API中`DrawText`函数的一个格式化标志。其含义是在指定矩形框内自动换行,当一行文本到达矩形框的右边界时,如果当前单词不能完整显示,会将该单词移到下一行继续显示。 使用场景方面,当需要在一个有限的矩形区域内显示较长的文本时,使用DT_WORDBREAK可以使文本更整齐地显示,避免文本溢出矩形区域。例如在对话框、消息框、文本显示区域等需要多行显示文本的地方,都可以使用DT_WORDBREAK标志来实现自动换行的效果。以下是一个简单的示例代码,展示了如何在`DrawText`函数中使用DT_WORDBREAK: ```cpp #include <windows.h> LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) { static TCHAR szAppName[] = TEXT("DrawTextExample"); HWND hwnd; MSG msg; WNDCLASS wndclass; wndclass.style = CS_HREDRAW | CS_VREDRAW; wndclass.lpfnWndProc = WndProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = hInstance; wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wndclass.lpszMenuName = NULL; wndclass.lpszClassName = szAppName; if (!RegisterClass(&wndclass)) { MessageBox(NULL, TEXT("This program requires Windows NT!"), szAppName, MB_ICONERROR); return 0; } hwnd = CreateWindow(szAppName, TEXT("DrawText with DT_WORDBREAK"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL); ShowWindow(hwnd, iCmdShow); UpdateWindow(hwnd); while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { HDC hdc; PAINTSTRUCT ps; RECT rect; switch (message) { case WM_PAINT: hdc = BeginPaint(hwnd, &ps); GetClientRect(hwnd, &rect); TCHAR szText[] = TEXT("This is a long text that will be automatically wrapped using DT_WORDBREAK."); DrawText(hdc, szText, -1, &rect, DT_WORDBREAK); EndPaint(hwnd, &ps); return 0; case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hwnd, message, wParam, lParam); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值