剑指Offer之Java算法习题精讲链表与字符串及数组
题目一
解法
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode removeElements(ListNode head, int val) { ListNode q = new ListNode(-1); ListNode a = q; q.next = head; while(q.next!=null){ if(q.next.val==val){ q.next = q.next.next; }else{ q = q.next; } } return a.next; } }
题目二
解法
class Solution { public boolean isIsomorphic(String s, String t) { if(s.length()!=t.length()){ return false; } for(int i =0;i<s.length();i++){ if(s.indexOf(s.charAt(i))!=t.indexOf(t.charAt(i))){ return false; } } return true; } }
题目三
解法
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public void deleteNode(ListNode node) { node.val = node.next.val; node.next = node.next.next; } }
题目四
解法
class Solution { public boolean isAnagram(String s, String t) { if(s.length()!=t.length()) return false; ArrayList<Character> list1 = new ArrayList<>(); ArrayList<Character> list2 = new ArrayList<>(); for (int i = 0; i < s.length(); i++) { list1.add(s.charAt(i)); } for (int i = 0; i < t.length(); i++) { list2.add(t.charAt(i)); } Collections.sort(list1); Collections.sort(list2); for (int i = 0; i < list1.size(); i++) { if (list1.get(i)!=list2.get(i)) return false; } return true; } } //要熟悉API class Solution { public boolean isAnagram(String s, String t) { if (s.length() != t.length()) { return false; } char[] str1 = s.toCharArray(); char[] str2 = t.toCharArray(); Arrays.sort(str1); Arrays.sort(str2); return Arrays.equals(str1, str2); } }
题目五
解法
class Solution { public int missingNumber(int[] nums) { Arrays.sort(nums); for (int i = 0; i < nums.length; i++) { if(i!=nums[i]){ return i; } } return nums.length; } }
题目六
解法
class Solution { public boolean wordPattern(String pattern, String s) { String[] split = s.split(" "); if(split.length!=pattern.length()) return false; int q = 0; for(int i =0;i<split.length;i++){ l: for(int w = 0;w<split.length;w++){ if(split[w].equals(split[i])){ q = w; break l; } } if(pattern.indexOf(pattern.charAt(i))!=q){ return false; } } return true; } }
到此这篇关于剑指Offer之Java算法习题精讲链表与字符串及数组的文章就介绍到这了,更多相关Java 链表内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)