# BasedLeetCode

LeetCode learning records based on Java,Kotlin,Python...Github 地址

### 14 编写一个函数来查找字符串数组中最长的公共前缀字符串

• Java 语言实现
    public static String longestCommonPrefix(String[] strs) {
if (strs.length == 0) {
return "";
}
if (strs.length == 1) {
return strs[0] == null ? "" : strs[0];
}
//找出数组中字符长度最短的字符串的长度（决定最多进行轮循比较的次数或者说是位数）
int minLength = Integer.MAX_VALUE;
for (String s : strs) {
if (minLength > s.length()) {
minLength = s.length();
}
}
boolean isCharEquals = true;
int i;//记录最后一位相等字符的位置
for (i = 0; i < minLength; i++) {
for (int j = 0; j < strs.length; j++) {
if (strs[0].charAt(i) != strs[j].charAt(i)) {
isCharEquals = false;
break;
}
}
if (!isCharEquals) {
break;
}
}
return strs[0].substring(0, i);
}

• Kotlin 语言实现

### 20 给定一个只包括 '('，')'，'{'，'}'，'['，']' 的字符串，判断字符串是否有效

• Java 语言实现
    public boolean isValid(String s) {
Stack<Character> characterStack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
characterStack.push('(');
}
if (s.charAt(i) == '[') {
characterStack.push('[');
}
if (s.charAt(i) == '{') {
characterStack.push('{');
}
if (s.charAt(i) == ')') {
if (!characterStack.isEmpty() && characterStack.pop() == '(') {
continue;
} else {
return false;
}
}
if (s.charAt(i) == ']') {
if (!characterStack.isEmpty() && characterStack.pop() == '[') {
continue;
} else {
return false;
}
}
if (s.charAt(i) == '}') {
if (!characterStack.isEmpty() && characterStack.pop() == '{') {
continue;
} else {
return false;
}
}
}
return characterStack.isEmpty();
}

• Kotlin 语言实现
    fun isValid(s: String): Boolean {
val charStack = ArrayList<Char>()
for (i in s.indices) {
if (s[i] == '(') {
}
if (s[i] == '[') {
}
if (s[i] == '{') {
}
if (s[i] == ')') {
if (!charStack.isEmpty() && charStack[charStack.lastIndex] == '(') {
charStack.removeAt(charStack.lastIndex)
continue
} else {
return false
}
}
if (s[i] == ']') {
if (!charStack.isEmpty() && charStack[charStack.lastIndex] == '[') {
charStack.removeAt(charStack.lastIndex)
continue
} else {
return false
}
}
if (s[i] == '}') {
if (!charStack.isEmpty() && charStack[charStack.lastIndex] == '{') {
charStack.removeAt(charStack.lastIndex)
continue
} else {
return false
}
}
}
return charStack.isEmpty()
}


### 26 删除排序数组中的重复项

• Java 语言实现
    public int removeDuplicates(int[] nums) {
if (nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return 1;
}
int index = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[i - 1]) {
nums[index++] = nums[i];
}
}
return index;
}

• Kotlin 语言实现
    fun removeDuplicates(nums: IntArray): Int {
if (nums.isEmpty()) return 0
if (nums.size == 1) return 1
var index = 1
for (i in 1 until nums.size) {
if (nums[i] != nums[i - 1]) {
nums[index++] = nums[i]
}
}
return index
}

posted @ 2018-04-14 15:17  SiberiaDante  阅读(421)  评论(0编辑  收藏