1。https://leetcode.com/problems/reverse-words-in-a-string/#/description,
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
两种解法:
public String reverseWords(String s) {
String[] words = s.trim().split(" +");
Collections.reverse(Arrays.asList(words));
return String.join(" ", words);
}
public String reverseWords(String sentence){
Stack<Character> sentenceStack = new Stack<>();
Stack<Character> wordStack = new Stack<>();
StringBuilder sb = new StringBuilder();
if (sentence != null && sentence != " ") {
int i =0;
char c;
while (i < sentence.length()) {
c = sentence.charAt(i);
if (c != ' ') {
wordStack.add(c);
} else{
if (!wordStack.empty()) {
while(!wordStack.empty()) {
sentenceStack.add(wordStack.pop());
}
sentenceStack.add(' ');
}
}
i++;
}
while (!wordStack.empty()) {
sentenceStack.add(wordStack.pop());
}
if (!sentenceStack.empty() && sentenceStack.size() > 1 && sentence.charAt(sentence.length() - 1) == ' ') {
sentenceStack.pop();
}
while (!sentenceStack.empty()) {
sb.append(sentenceStack.pop());
}
}
return sb.toString();
}
2.
//给定一个乱序数组,找出和最大的子序列,并且计算和
public static void m2(){
int[]ints = {-1,3,-2,2,6,-1,3,-7,3,2,4};
// int[]ints ={-1,-3,-2,-2,-6,-100,-3,-7,-3,-2,-4};
int N =ints.length;
int max =ints[0];
int that = 0;
// int j = 0, k = 0;
for(inti = 0;i< N;i++) {
that+=ints[i];
if(that > max){
max = that;
// k =i;
// if(j == 0 && k > 0){
// j = k;
// }
}elseif(that < 0){
that = 0;
// if(k >i){
// j =i;
// }
}
}
System.out.println(max);
// System.out.println(j +"----"+ k);开始和结束位置
}
3.快速排序
class Quick{
publicstatic void main(String[]args){
intarr[] = {1, 3, 2, 9, 6, 8, 4, 7, 5, 0};
sort(arr, 0, 9);
for(int a :arr){
System.out.print(a);
}
}
staticvoid sort(int[] v,intleft,int right){
if(left < right){
int key = v[left];
int low = left;
int high = right;
while(low < high){
while(low < high && v[high] > key){
high--;
}
v[low] = v[high];
while(low < high && v[low] < key){
low++;
}
v[high] = v[low];
}
v[low] = key;
sort(v, left, low - 1);
sort(v,low+1,right);
}
}
}
4.二叉树的层序遍历
public staticvoid test(List<Tree> trees){
if(trees== null){
return;
}
int cur = 0;
int last = 1;
while(cur< trees.size()){
last =trees.size();
while(cur < last){
System.out.print(trees.get(cur).getData());
if(trees.get(cur).getTreeLeft() != null)
trees.add(trees.get(cur).getTreeLeft());
if(trees.get(cur).getTreeRight() != null)
trees.add(trees.get(cur).getTreeRight());
cur++;
}
System.out.println();
}
}
5.//判断一个数是不是快乐数字
public class Solution{
public long sumSquare(long n){
long sum = 0;
while(n!=0){
sum += Math.pow(n%10,2);
n= n/10;
}
returnsum;
}
public booleanisHappy(int n){
if(n<0)
return false;
long nn = n ;
Set<Long> set = new HashSet<Long>();
while(true){
if(set.contains(nn)){
return false;
}else{
set.add(nn);
}
nn =sumSquare(nn);
if(nn==1)
return true;
}
}
}