Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add JS solution for 0027,0058,0234 #165

Merged
merged 2 commits into from
Apr 26, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions solution/0027.Remove Element/Solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
var removeElement3 = function (nums, val) {
let len = nums.length
if (len < 1) {
return 0
}

let i = 0
while (i < len) {
if (nums[i] === val) {
nums[i] = nums[len - 1]
len--
} else {
i++
}
}
return len
};

var removeElement2 = function (nums, val) {
let i = 0
for (let j = 0; j < nums.length; j++) {
if (nums[j] !== val) {
nums[i] = nums[j]
i++
}
}
return i
}

var removeElement = function (nums, val) {
let len = nums.length;
for (let i = 0; i < len; i++) {
if (nums[i] === val) {
nums.splice(i, 1);
i--;
}
}
return len;
}
16 changes: 16 additions & 0 deletions solution/0058.Length of Last Word/Solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
var lengthOfLastWord = function (s) {
s = s.trim()
return s.length - s.lastIndexOf(" ") - 1
};

var lengthOfLastWord2 = function (s) {
let res = 0
for (let i = 0; i < s.length; i++) {
if (s[i] !== ' ' && (i === 0 || s[i - 1] === ' ')) {
res = 1
} else if (s[i] !== ' ') {
res++
}
}
return res
}
58 changes: 58 additions & 0 deletions solution/0234.Palindrome Linked List/Solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
var isPalindrome2 = function (head) {
if (!head || !head.next) {
return true
}
let slow = head
let fast = head
while (fast !== null && fast.next !== null) {
slow = slow.next
fast = fast.next.next
}
if (fast !== null) {
slow = slow.next
}

let p = new ListNode(0)
while (slow !== null) {
let t = slow.next
slow.next = p.next
p.next = slow
slow = t
}

let left = head
let right = p.next
while (right !== null) {
if (left.val !== right.val) {
return false
}
left = left.next
right = right.next
}
return true
};

var isPalindrom3 = function (head) {
let arr = [];
let next = head;
while (next) {
arr.push(next.val);
next = next.next;
}
let len = Math.trunc(arr.length / 2);
for (let i = 0; i < len; i++) {
if (arr[i] !== arr[arr.length - 1 - i]) {
return false;
}
}
return true;
}

var isPalindrome = function (head) {
let arr = []
while (head) {
arr.push(head.val)
head = head.next
}
return arr.join('') === arr.reverse().join('')
}