| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -1 +1,2 @@ | |||
| 1 | - /build/ | ||
| 1 | + build/ | ||
| 2 | + | ||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -0,0 +1,82 @@ | |||
| 1 | + package containers; | ||
| 2 | + | ||
| 3 | + import java.util.ArrayList; | ||
| 4 | + import java.util.Arrays; | ||
| 5 | + import java.util.Collection; | ||
| 6 | + import java.util.Iterator; | ||
| 7 | + | ||
| 8 | + /** | ||
| 9 | + * 利用迭代器实现字符串反转 | ||
| 10 | + * | ||
| 11 | + * @author liuyuning | ||
| 12 | + * | ||
| 13 | + * | ||
| 14 | + */ | ||
| 15 | + public class Reverse { | ||
| 16 | + @SuppressWarnings("serial") | ||
| 17 | + private static class ReverseCollection<T> extends ArrayList<T> { | ||
| 18 | + | ||
| 19 | + public ReverseCollection(Collection<T> collection) { | ||
| 20 | + super(collection); | ||
| 21 | + } | ||
| 22 | + | ||
| 23 | + public Iterable<T> reverse() { | ||
| 24 | + return new Iterable<T>() { | ||
| 25 | + | ||
| 26 | + @Override | ||
| 27 | + public Iterator<T> iterator() { | ||
| 28 | + return new Iterator<T>() { | ||
| 29 | + int current = size() - 1; | ||
| 30 | + | ||
| 31 | + @Override | ||
| 32 | + public boolean hasNext() { | ||
| 33 | + return current > -1; | ||
| 34 | + } | ||
| 35 | + | ||
| 36 | + @Override | ||
| 37 | + public T next() { | ||
| 38 | + return get(current--); | ||
| 39 | + } | ||
| 40 | + }; | ||
| 41 | + } | ||
| 42 | + }; | ||
| 43 | + } | ||
| 44 | + | ||
| 45 | + } | ||
| 46 | + | ||
| 47 | + /** | ||
| 48 | + * | ||
| 49 | + * @param s | ||
| 50 | + * @return | ||
| 51 | + */ | ||
| 52 | + public static String reverseWords(String s) { | ||
| 53 | + ReverseCollection<String> reverseCollection = new ReverseCollection<String>(Arrays.asList(s.split(" "))); | ||
| 54 | + StringBuilder stringBuilder = new StringBuilder(); | ||
| 55 | + for (String word : reverseCollection.reverse()) { | ||
| 56 | + stringBuilder.append(word + " "); | ||
| 57 | + } | ||
| 58 | + return stringBuilder.toString().trim(); | ||
| 59 | + | ||
| 60 | + } | ||
| 61 | + | ||
| 62 | + /** | ||
| 63 | + * | ||
| 64 | + * @param i | ||
| 65 | + * @Todo reverse int value | ||
| 66 | + */ | ||
| 67 | + public static int reverseInt(int i) { | ||
| 68 | + boolean isNegative = false; | ||
| 69 | + | ||
| 70 | + if (i < 0) { | ||
| 71 | + isNegative = true; | ||
| 72 | + i = -i; | ||
| 73 | + } | ||
| 74 | + return i; | ||
| 75 | + | ||
| 76 | + } | ||
| 77 | + | ||
| 78 | + public static void main(String[] args) { | ||
| 79 | + String s = "This is a test for reversing words"; | ||
| 80 | + System.out.println(reverseWords(s)); | ||
| 81 | + } | ||
| 82 | + } | ||
| Back | FazBrowse Home | New Git URL |
0 commit comments