Edit Distance
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character b) Delete a character c) Replace a character
思路:动态规划。
D[i+1][j+1] = D[i][j]; word1[i] == word2[j],
D[i+1][j+1] = min(min(D[i][j+1], D[i+1][j]), D[i][j]) + 1; otherwise.
class Solution { public: int minDistance(string word1, string word2) { vector<vector<int> > D(word1.size()+1, vector<int>(word2.size()+1, 0)); for(int j = 0; j <= word2.size(); ++j) D[0][j] = j; for(int i = 0; i <= word1.size(); ++i) D[i][0] = i; for(int i = 0; i < word1.size(); ++i) { for(int j = 0; j < word2.size(); ++j) { if(word1[i] == word2[j]) D[i+1][j+1] = D[i][j]; else D[i+1][j+1] = min(min(D[i][j+1], D[i+1][j]), D[i][j]) + 1; } } return D[word1.size()][word2.size()]; } };
Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example, path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
Corner Cases:
- Did you consider the case where path =
"/../"
? In this case, you should return"/"
. - Another corner case is the path might contain multiple slashes
'/'
together, such as"/home//foo/"
. In this case, you should ignore redundant slashes and return"/home/foo"
.
注意: /..., /.home, /..h2me, /ho_Me/... 为合法路径。
思路: 从头往尾读: 如是 / 和字符,数字,下划线 , 好判断。若是 '.', 则分情况即可。
inline bool isAlpha(char ch) { return(('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z')); } inline bool isAlphaOrUnderline(char ch) { return isAlpha(ch) || (ch == '_'); } inline bool isValid(char ch) { return isAlphaOrUnderline(ch) || ('0' <= ch && ch <= '9'); } class Solution {// the first alpha should be '/' public: string simplifyPath(string path) { string ans; path.insert(0, 1, '/'); // but without this state. is OK too. for(size_t i = 0; i < path.size(); ++i) { if(path[i] == '.') { if(i < path.size()-1 && isAlphaOrUnderline(path[i+1])) { ans.push_back('.'); continue;} else if(i < path.size()-2 && path[i+1] == '.' && (isAlphaOrUnderline(path[i+2]) || path[i+2] == '.')) { i += 2; ans.insert(ans.size(), 2, '.'); ans.push_back(path[i]); continue; } } if(path[i] == '/' && !ans.empty() && ans.back() == '/') continue; if('0' <= path[i] && path[i] <= '9' && !ans.empty() && ans.back() == '/') continue; if(path[i] == '/' || isValid(path[i])) ans.push_back(path[i]); else if(path[i] == '.' && i < path.size()-1 && path[i+1] == '.') { ++i; if(ans.size() > 1 && ans.back() == '/') ans.pop_back(); while(!ans.empty() && ans.back() != '/') ans.pop_back(); } } if(ans.size() > 1 && ans.back() == '/')ans.pop_back(); return ans; } };