不是最优解,基于自己能够理解的解法写,主要记录自己第一次刷力扣自己或者学习别人的答题思路
一、最长公共前缀
解题思路:先去匹配两个字符串中共同字符串,再去匹配其他的字符串即可
public String longestCommonPrefix(String[] strs) {
String temp = strs[0];
for(int i = 1 ; i < strs.length; i ++){
int j = 0;
int count = Math.min(temp.length(),strs[i].length());
for(; j < count; j++){
if(temp.charAt(j) != strs[i].charAt(j)){
break;
}
}
temp = temp.substring(0,j);
}
return temp;
}
二、最后一个单词的长度
解题思路:虽然可以上来就trim,split、length,思考了一下可以向前遍历
public int lengthOfLastWord(String s) {
s = s.trim();
if(s.length() == 1){
return 1;
}
int count = 0;
for(int i = s.length()-1; i > -1 ; i--){
if(s.charAt(i) == ' '){
break;
}
count++;
}
return count;
}
三、反转字符串里的单词
思路一:使用split,然后找个栈,放进去 再出栈,但是属于O(2n)了=-=
public String reverseWords(String s) {
s = s.trim();
String[] s1 = s.split(" ");
Stack<String> stack = new Stack<>();
for(int i = 0 ; i < s1.length; i++){
stack.push(s1[i]);
}
StringBuffer sb = new StringBuffer();
while(!stack.empty()){
sb.append(" "+stack.pop());
}
return sb.toString().trim();
}
思路二:前序遍历,使用双指针来截取字串、在append即可
public String reverseWords2(String s) {
int left = s.length() - 1;
int right = s.length() - 1;
StringBuffer res = new StringBuffer();
while(left > -1) {
//去掉多余空格
while (left >= 0 && s.charAt(left) == ' ') {
left--;
}
right = left; //确定字串结尾
//找到字串起始
while(left >= 0 && s.charAt(left) != ' '){
left--;
}
res.append(s.substring(left + 1, right + 1));
//一个单词之后添加一个空格
res.append(' ');
}
return res.deleteCharAt(res.length() - 1).toString();
}