Java字符串常见编程题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kaikai_sk/article/details/83012865

Z形排列字符串

Description
The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P A H N
A P L S I I G
Y I R
And then read line by line: “PAHNAPLSIIGYIR”

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);
Example 1:

Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
Example 2:

Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:

P I N
A L S I G
Y A H R
P I
Tags: String

	public String convert(String s, int numRows)
	{
		if(numRows <= 1)
			return s;
		int len = s.length();
		char[] chars = s.toCharArray();
		StringBuilder[] sbs = new StringBuilder[numRows];
		for(int i=0;i<numRows;i++)
		{
			sbs[i] = new StringBuilder();
		}
		
		int i=0;
		while(i<len)
		{
			for(int j=0;j<numRows && i<len; j++)
			{
				sbs[j].append(chars[i++]);
			}
			for(int j=numRows-2;j>=1 && i<len ; j--)
			{
				sbs[j].append(chars[i++]);
			}
		}
		
		for(i=1;i<numRows;i++)
		{
			sbs[0].append(sbs[i]);
		}
		
		return sbs[0].toString();
	}

atoi

String to Integer (atoi)

import java.util.*;
import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

class Solution
{
	public static void main(String[] args) 
	{
		System.out.println(new Solution().myAtoi(" "));
	}
	
	public int myAtoi(String str)
	{
		if("".equals(str))
		{
			return 0; 
		}
		
		int i=0,sign=1,len=str.length();
		long ans = 0;
		
		//过滤空格		
		while(i<len && str.charAt(i) ==' ')
		{
			i++;
		}
		if(i<len && ( (str.charAt(i) == '-') || (str.charAt(i)=='+')))
		{
			sign = str.charAt(i++) == '+' ? 1: -1;
		}
		for(; i<len;i++)
		{
			int tmp = str.charAt(i) - '0';
			if(tmp <0 || tmp > 9)
				break;
			ans = ans * 10 +tmp;
			if( ans > Integer.MAX_VALUE)
			{
				if(sign == -1)
					return sign * (Integer.MAX_VALUE+1);
				else if (sign == 1)
					return sign * (Integer.MAX_VALUE);
			}
			
		}
		return (int)(sign * (int) ans);
		
	}
}

猜你喜欢

转载自blog.csdn.net/kaikai_sk/article/details/83012865