加油 回文串

This commit is contained in:
Zerroi 2024-03-10 20:15:29 +08:00
parent c1c43f75f5
commit 39cb705c71
3 changed files with 129 additions and 0 deletions

View File

@ -0,0 +1,35 @@
package com.zerroi.leetcode.ThreeNine;
public class ProductExceptSelf {
public static void main(String[] args) {
SolutionFirst solutionFirst = new SolutionFirst();
int[] ints = solutionFirst.productExceptSelf(new int[]{1, 2, 3, 4});
}
}
/*
给你一个整数数组 nums返回 数组 answer 其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积
题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 整数范围内
不要使用除法且在 O(n) 时间复杂度内完成此题
*/
class SolutionFirst {
public int[] productExceptSelf(int[] nums) {
int length = nums.length;
int[] res = new int[length];
int temp = 1;
for (int i = 0; i < length; i++) {
res[i] = temp;
temp = temp * nums[i];
}
int a = 1;
for (int i = length - 1; i >= 0; i--) {
res[i] = res[i] * a;
a = a * nums[i];
}
return res;
}
}

View File

@ -0,0 +1,37 @@
package com.zerroi.leetcode.ThreeTen;
import java.util.Arrays;
public class CanCompleteCircuit {
public static void main(String[] args) {
SolutionFirst solutionFirst = new SolutionFirst();
int res = solutionFirst.canCompleteCircuit(new int[]{2,1,5,3,3,4}, null);
System.out.println("res = " + res);
}
}
/*
在一条环路上有 n 个加油站其中第 i 个加油站有汽油 gas[i]
你有一辆油箱容量无限的的汽车从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 你从其中的一个加油站出发开始时油箱为空
给定两个整数数组 gas cost 如果你可以按顺序绕环路行驶一周则返回出发时加油站的编号否则返回 -1 如果存在解 保证 它是 唯一
*/
class SolutionFirst {
public int canCompleteCircuit(int[] gas, int[] cost) {
int cur = 0;
int station = 0;
int stock = 0;
for (int i = 0; i < gas.length; i++) {
stock += gas[i] - cost[i];
cur += gas[i] - cost[i];
if (cur < 0) {
station = i + 1;
cur = 0;
}
}
if (stock < 0) {
return -1;
}
return station;
}
}

View File

@ -0,0 +1,57 @@
package com.zerroi.leetcode.ThreeTen;
public class IsPalindrome {
public static void main(String[] args) {
SolutionSecond solutionSecond = new SolutionSecond();
solutionSecond.isPalindrome("race a car");
}
}
class SolutionSecond {
public boolean isPalindrome(String s) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ((c >= 65 && c <= 90) || (c >= 97 && c <= 122) || (c >= 48 && c <= 59)) {
builder.append(String.valueOf(c).toLowerCase());
}
}
String str = builder.toString();
return builder.reverse().toString().equals(str);
}
public boolean isPalindromeTow(String s) {
class Solution {
public boolean isPalindrome(String s) {
boolean ans = true;
int l = 0;
int r = s.length() - 1;
while (true) {
if (l > r) {
break;
}
char lc = s.charAt(l);
char rc = s.charAt(r);
if (!Character.isLetterOrDigit(lc)) {
l++;
continue;
}
if (!Character.isLetterOrDigit(rc)) {
r--;
continue;
}
if (Character.toLowerCase(lc) == Character.toLowerCase(rc)) {
l++;
r--;
} else {
ans = false;
break;
}
}
return ans;
}
}
}
}