https://leetcode.com/problems/palindrome-number/description/
class Solution { public int reverse(int x) { int mod =10; x = Math.abs(x); long resulting_number = 0; while(Math.abs(x) > 0) { resulting_number = resulting_number *mod; resulting_number +=x % mod; x = x / mod; } if(resulting_number > Integer.MAX_VALUE) return 0; return (int)resulting_number; } public boolean isPalindrome(int x) { if(x == reverse(x)) return true; else return false; } }
1 Comment
https://leetcode.com/problems/valid-parentheses/description/
import java.util.Stack; class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); for(int i = 0; i < s.length(); ++i) { if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') { stack.push(s.charAt(i)); } else { if(stack.isEmpty()) return false; if(s.charAt(i) == ')' && stack.peek() != '('){return false;} if(s.charAt(i) == '}' && stack.peek() != '{'){return false;} if(s.charAt(i) == ']' && stack.peek() != '['){return false;} stack.pop(); } } if(stack.isEmpty()) return true; else return false; } public static void main(String[] args) { Solution s = new Solution(); String test_string = "([)]"; System.out.println(s.isValid(test_string)); } }
https://leetcode.com/problems/merge-two-sorted-lists/description/
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode result = null; ListNode last = null; ListNode l3=null; while(l1 != null || l2!=null){ if(l1 != null){ if(l2 != null){ if(l1.val <= l2.val){ l3 = new ListNode(l1.val); l1 = l1.next; } else{ l3 = new ListNode(l2.val); l2 = l2.next; } } else{ l3 = new ListNode(l1.val); l1 = l1.next; } } else{ l3 = new ListNode(l2.val); l2 = l2.next; } if(result == null){ result = l3; last = l3; } else{ last.next = l3; last = last.next; } } return result; } }
https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
class Solution { public int removeDuplicates(int[] nums) { if(nums.length < 1) return 0; int len = 0; int cur = nums[0]; int cur_ind = 0; for(int i =1; i < nums.length; ++i){ if(nums[i] != cur){ len+=1; cur = nums[i]; cur_ind +=1; System.out.println(nums[cur_ind]=cur); } } Arrays.copyOfRange(nums, 0, len); return len + 1; } } |
This is a collection of interview prep programs, online resources that were used in my Java classes. The Java classes were taught years ago, hence the material is likely outdated, I will make an effort to go through it and update as time permits Categories |