本篇是记录在刷题时遇到的自己不常用的String类的方法, 持续记录中…
startsWith(String prefix, int toffset)
public boolean startsWith(String prefix, int toffset) {
char ta[] = value;
int to = toffset;
char pa[] = prefix.value;
int po = 0;
int pc = prefix.value.length;
// Note: toffset might be near -1>>>1.
if ((toffset < 0) || (toffset > value.length - pc)) {
return false;
}
while (--pc >= 0) {
if (ta[to++] != pa[po++]) {
return false;
}
}
return true;
}
public boolean startsWith(String prefix) {
return startsWith(prefix, 0);
}
startsWith(String prefix)判断prefix是否是字符串的前缀,其内部调用startsWith(String prefix, int toffset),该方法相当于this.substring(toffset).startsWith(prefix),即判断prefix是否是字符串子串的前缀。
来看看其在一个算法题中的运用:
LeetCode139.:Word Break
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.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
两种思路:动态规划和回溯
动态规划:boolean dp[ i ] 表示string[ 0 ~ i-1 ] 能否被dict组成。则dp[ i+1 ]的值?遍历dp[ 0 ~ i ] 找到dp[ j ] == true,判断string[ j ~ i] 是否在dict里。
public boolean wordBreak(String s, List<String> wordDict){
boolean[] dp = new boolean[s.length()+1];
dp[0] = true;
for (int i = 1; i <= s.length(); i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && wordDict.contains(s.substring(j, i))){
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
backingtracking解法
public boolean wordBreak2(String s, List<String> wordDict) {
return backtracking(s, wordDict, 0, new boolean[s.length()]);
}
// i : 代表递归的当前位置;unbreakable:是为了避免重复计算,
// 以加快算法,unbreakable[i] 为true,代表dict中无法组合成
// s[i ~ END]
private boolean backtracking(String s, List<String> dict, int i, boolean[] unbreakable) {
if (i == s.length()) return true;
if (unbreakable[i]) return false;
// 每次递归都遍历dict,检查dict是否存在s[i ~ END]的前缀
for(String string : dict){
if (!s.startsWith(string, i)) continue;
if (backtracking(s, dict, i+string.length(), unbreakable)) return true;
}
unbreakable[i] = true;
return false;
}