LeetCode基础题——字符串篇

一共也是10题,时间关系,先上7题,明天再补

package leetcode;

public class StringProblems {

    public static void reverseString(char[] s) {
        int len = s.length;
        for (int i = 1; i <= s.length / 2; i++) {
            int idx = (len - i);
            char tmp = s[idx];
            s[idx] = s[i - 1];
            s[i - 1] = tmp;
        }
    }

    /**
     * 这里方法上其实跟上面反转字符串有异曲同工之妙
     * @param x
     * @return
     */
    public static int reverse(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            //防止上溢
            if (rev>Integer.MAX_VALUE/10||(rev==Integer.MAX_VALUE/10&&pop>7))
                return 0;
            //防止下溢
            if (rev>Integer.MIN_VALUE/10||(rev==Integer.MIN_VALUE/10&&pop<-8))
                return 0;
            rev=rev*10+pop;
        }
        return rev;
    }

    /**
     * 字符串中的第一个唯一字符
     * @param s
     * @return
     */
    public static int firstUniqChar(String s){
        //用于记录某个字符出现的次数,因为只有26个字母,所以只用长度26即可
        int freq[]=new int [26];
        for (int i = 0; i = 'a' && pre <= 'z' || pre >= '0' && pre <= '9')) {
                startIndex++;
                continue;
            }
            //如果不是字母或数字,则直接跳过
            if (!(aft >= 'a' && aft <= 'z' || aft >= '0' && aft <= '9')) {
                endIndex--;
                continue;
            }
            if (pre != aft)
                return false;
            startIndex++;
            endIndex--;
        }
        return true;
    }

	/**
	* 将字符串转化为整数,字符串中开头可以包含空格
	*/
	public static int myAtoi(String str) {
        if (str.isEmpty()) return 0;
        //符号位
        int sign = 1;
        //转换值
        int base = 0;
        //索引位
        int i = 0;
        //跳过空格
        while (i= '0' && str.charAt(i) <= '9') {
	        //处理溢出
            if (base > Integer.MAX_VALUE / 10 || (base == Integer.MAX_VALUE / 10 && str.charAt(i) - '0' > 7)) {
                return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            base = 10 * base + (str.charAt(i++) - '0');
        }
        return base * sign;
    }

	/**
     * 实现 strStr() 函数。
     * 

* 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。 * 遍历母字符串,我们并不需要遍历整个母字符串,而是遍历到剩下的长度和子字符串相等的位置即可,这样可以提高运算效率。 * 然后对于每一个字符,我们都遍历一遍子字符串,一个一个字符的对应比较,如果对应位置有不等的,则跳出循环,如果一直都没有跳出循环,则说明子字符串出现了,则返回起始位置即可 * @param str * @param needle * @return */ public static int strStr(String haystack, String needle) { if (needle.isEmpty()) return 0; int m = haystack.length(); int n = needle.length(); if (m < n) return -1; //i为子串的起始位置,起始位置不能大于m-n for (int i = 0; i <= m - n; i++) { int j = 0; //j是子串的指针用来对子串进行遍历 for (j = 0; j < n; j++) { if (haystack.charAt(i + j) != needle.charAt(j)) break; } if (j == n) return i; } return -1; } public static void main(String[] args) { char[] s = {'h', 'e', 'l', 'l', 'o'}; StringProblems.reverseString(s); } }

你可能感兴趣的:(数据结构和算法——Java实现)