不清楚這道題是不是亞信科技的原創題目,貌似在網上看到微軟的筆試也有這道題目。原題的是c語言解決的,考慮java熟練一些。自己就有java來寫這道題的算法。
題目描寫敘述:編寫一個確定字符串在還有一個字符串中出現的次數的算法。
比如字符串“this”在字符串”this is my first program, this…”中出現了2次。不要使用庫函數(方法)。
解題思路:寫一個靜態方法。先取出要查找的字符串的第一個字母,然后再拿到字符串中去搜尋,當字符串中出現字母與要查找的首字母吻合。我們就做標記。然后用剩余的字符逐步比較。四個字符都吻合,計數器變量count自增。
public class FindStr {
public static void main(String[] args) {
String strToFind = "this";
String str = "this,this thi s my first program, this is my java...";
System.out.println(countAppea(strToFind, str));
}
public static int countAppea(String str2Find, String str) {
int count = 0;
for(int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
boolean flag = false;
if(str2Find.charAt(0) == c) {
flag = true;
int index = i;
for(int j = 0; j < str2Find.length(); j++, index++) {
if(str2Find.charAt(j) != str.charAt(index)) {
flag = false;
break;
}
}
if(flag) {
count ++;
}
}
}
return count;
}
}
執行結果:
3
由於我的字符串里面有四個this,當中有一個事有益分開的。所以有三個this!