剑指 Offer 06. 从尾到头打印链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
Stack<Integer> stack = new Stack<>();
int count = 0;
while(head != null){
stack.push(head.val);
head = head.next;
count++;
}
int[] num = new int[count];
int i = 0;
while(!stack.isEmpty()){
num[i] = stack.pop();
i++;
}
return num;
}
}
剑指 Offer 50. 第一个只出现一次的字符
方法一:
class Solution {
public char firstUniqChar(String s) {
if(s.equals("")) return ' ';
char res = ' ';
int[] zm = new int[26];
for(int i=0;i<s.length();i++){
zm[s.charAt(i)-'a']++;
}
for(int i=0;i<s.length();i++){
if(zm[s.charAt(i)-'a'] == 1){
res = s.charAt(i);
break;
}
}
return res;
}
}
方法二:哈希表
class Solution {
public char firstUniqChar(String s) {
if(s.equals(" ")) return ' ';
char res = ' ';
HashMap<Character,Integer> map = new HashMap<>();
char[] s2 = s.toCharArray();
for(char c : s2){
map.put(c,map.getOrDefault(c,0) + 1);
}
for(char c: s2){
if(map.get(c) == 1){
res = c;
break;
}
}
return res;
}
}
58. 最后一个单词的长度
方法一:
class Solution {
public int lengthOfLastWord(String s) {
//按照正则表达式来以空格分割字符串
String[] str = s.split("\\s+");
int n = str.length;
return str[n-1].length();
}
}
方法二:
class Solution {
public int lengthOfLastWord(String s) {
int n = s.length();
int j = n;
while(j-1 >= 0 && s.charAt(j-1) == ' '){
j--;
}
int i = j;
//这里忘记加i-1 >= 0导致出现溢出报错
while(i-1 >= 0 && s.charAt(i-1) != ' '){
i--;
}
return j-i;
}
}
这篇博客介绍了三种不同的编程问题解决方案:1) 链表的从尾到头打印,使用栈实现;2) 字符串中第一个只出现一次的字符查找,分别通过数组计数和哈希表实现;3) 计算字符串最后一个单词的长度,采用正则表达式和双指针方法。这些方法展示了基础数据结构和算法的应用。

被折叠的 条评论
为什么被折叠?



