Skip to content

Commit f078401

Browse files
Xuemeng ZhangXuemeng Zhang
Xuemeng Zhang
authored and
Xuemeng Zhang
committed
May 19, 2018
1 parent b1543aa commit f078401

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed

139_Word_Break.cpp

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
3+
4+
Note:
5+
6+
The same word in the dictionary may be reused multiple times in the segmentation.
7+
You may assume the dictionary does not contain duplicate words.
8+
Example 1:
9+
10+
Input: s = "leetcode", wordDict = ["leet", "code"]
11+
Output: true
12+
Explanation: Return true because "leetcode" can be segmented as "leet code".
13+
Example 2:
14+
15+
Input: s = "applepenapple", wordDict = ["apple", "pen"]
16+
Output: true
17+
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
18+
Note that you are allowed to reuse a dictionary word.
19+
Example 3:
20+
21+
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
22+
Output: false
23+
*/
24+
#include <vector>
25+
#include <string>
26+
using namespace std;
27+
28+
class Solution {
29+
public:
30+
bool wordBreak(string s, vector<string>& wordDict) {
31+
int *p = new int[s.length()+1];
32+
for(int i=0; i<=(int)s.length(); ++i) p[i] = 0;
33+
p[0] = 1;
34+
for(int i=1; i<=(int)s.length(); ++i){
35+
for(vector<string>::iterator iter = wordDict.begin(); \
36+
iter != wordDict.end(); ++iter){
37+
int j = i - iter->size();
38+
if( (0<=j) && p[j] && (s.substr(j, iter->size())==*iter) ){
39+
p[i] = 1;
40+
break;
41+
}
42+
}
43+
}
44+
bool result = p[s.length()];
45+
delete[] p;
46+
return result;
47+
}
48+
};

242_Valid_Anagram.cpp

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/*
2+
Given two strings s and t , write a function to determine if t is an anagram of s.
3+
4+
Example 1:
5+
6+
Input: s = "anagram", t = "nagaram"
7+
Output: true
8+
Example 2:
9+
10+
Input: s = "rat", t = "car"
11+
Output: false
12+
Note:
13+
You may assume the string contains only lowercase alphabets.
14+
15+
Follow up:
16+
What if the inputs contain unicode characters? How would you adapt your solution to such case?
17+
18+
*/
19+
#include <string>
20+
#include <vector>
21+
using namespace std;
22+
23+
class Solution {
24+
public:
25+
bool isAnagram(string s, string t) {
26+
//check the length
27+
if(s.length()!=t.length()) return false;
28+
//build counting table
29+
int counts[26] = {0};
30+
for(size_t i=0; i<s.length(); ++i){
31+
counts[s[i]-'a']++;
32+
counts[t[i]-'a']--;
33+
}
34+
//check if counting table only contains zeros
35+
for(size_t i=0; i<26; ++i){
36+
if(counts[i]) return false;
37+
}
38+
//return
39+
return true;
40+
}
41+
};

0 commit comments

Comments
 (0)