严氏北美IT公司面试真题汇总和解答论坛
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Reverse Words In AStringII

Go down

Reverse Words In AStringII Empty Reverse Words In AStringII

Post by Admin Sat Oct 21, 2017 5:38 pm

public String reverseWords(String s){
char[] s_char=s.toCharArray();
int last=0;
for(int i=0;i<s_char.length;i++){
if(s_char[i]==' '){
reverse(s_char,last,i-1);
last=i+1;
}
}
reverse(s_char,last,s_char.length-1);
reverse(s_char,0,s_char.length-1);
return new String(s_char);
}

public void reverse(char[] s, int i, int j){
while(i<j){
char tmp=s[i];
s[i]=s[j];
s[j]=tmp;
i++;
j--;
}
}


public static void main(String[] args) {
// TODO Auto-generated method stub
String s="The sky is blue";
ReverseWordsInAStringII test=new ReverseWordsInAStringII();
String res=test.reverseWords(s);
System.out.println(res);
}

Admin
Admin

Posts : 124
Join date : 2017-10-21

https://csinterviewquestions.forumotion.com

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum